iOS 刮奖

前段时间公司项目提了个刮奖需求,网上找了很多,不过大多不能用,或者不合适。所以参考网友代码自己写了一个 Demo

先看下效果图
2019-12-02 20.10.12.gif

关于在TableView中刮奖时的手势冲突,可以这样解决
写一个类继承UITableView,重写手势代理方法

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"YLScratchMaskView"]) {
        return NO;      //关闭手势
    }
    return YES;
}

使用代码


- (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);
    
}

实现的核心代码

//获取透明像素占总像素的百分比
- (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);
}

你可能感兴趣的:(iOS 刮奖)