前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS 刮奖

iOS 刮奖

作者头像
Raindew
发布2019-12-24 15:13:41
4180
发布2019-12-24 15:13:41
举报
前段时间公司项目提了个刮奖需求,网上找了很多,不过大多不能用,或者不合适。所以参考网友代码自己写了一个 Demo地址
先看下效果图

2019-12-02 20.10.12.gif

使用代码

代码语言:javascript
复制
- (void)viewDidLoad {
    [super viewDidLoad];
    //创建刮刮卡组件
    self.scratchView = [[YLScratchView alloc] initWithFrame:CGRectMake(20, 120, self.view.frame.size.width - 40, 126) backImage:[UIImage imageNamed:@"result_image"] mask:[UIImage imageNamed:@"mask"] scratchWidth:30 scratchType:kCGLineCapSquare];
    self.scratchView.delegate = self;
    [self.view addSubview:self.scratchView];
    
}

- (void)scratchView:(YLScratchView *)scratchView beganPoint:(CGPoint)point {
    NSLog(@"开始刮奖 %f,%f",point.x,point.y);
}

- (void)scratchView:(YLScratchView *)scratchView movedProgress:(CGFloat)progress {
    NSLog(@"刮奖百分比:%f",progress);
    if (progress>=0.25) {//百分之25
        [self.scratchView.scratchMask removeFromSuperview];
    }
}

- (void)scratchView:(YLScratchView *)scratchView endedPoint:(CGPoint)point {
    NSLog(@"刮奖结束%f,%f",point.x,point.y);
    
}

实现的核心代码

代码语言:javascript
复制
//获取透明像素占总像素的百分比
- (CGFloat)getAlphaPixelPercent:(UIImage *)img {
    
    //计算像素总个数
    NSInteger width = img.size.width;
    NSInteger height = img.size.height;
    NSInteger bitmapByteCount = width * height;
    unsigned char *pixelData = malloc(bitmapByteCount * 4);


    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(pixelData, width, height, 8, width, colorSpace, kCGImageAlphaOnly);
    CGRect rect = CGRectMake(0, 0, width, height);
    CGContextClearRect(context, rect);
    CGContextDrawImage(context, rect, img.CGImage);
    //计算透明像素个数
    NSInteger alphaPixelCount = 0;
    for (NSInteger y=0;y < height;y ++) {
        for (NSInteger x=0;x < width;x ++) {
            if (pixelData[y * width + x] == 0) {
                alphaPixelCount += 1;
            }
        }
    }
    
    free(pixelData);
    return ((CGFloat)alphaPixelCount) / ((CGFloat)bitmapByteCount);
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前段时间公司项目提了个刮奖需求,网上找了很多,不过大多不能用,或者不合适。所以参考网友代码自己写了一个 Demo地址
    • 先看下效果图
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档