2019-12-02 20.10.12.gif
使用代码
- (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);
}