目前很多項(xiàng)目中都會(huì)用到“刮刮樂”這個(gè)功能點(diǎn)宴猾,處于此整理出了一套比較easy的實(shí)現(xiàn)方法册倒。
在這里我主要用到了ImageMaskView這個(gè)類泊窘,下面來說說具體操作:
將項(xiàng)目中的Tools工具直接拖入到工程槽惫,ImageMaskView類作為VC的一個(gè)屬性并遵循ImageMaskFilledDelegate的代理方法:
@interface ViewController ()<ImageMaskFilledDelegate>
@property(nonatomic, strong)ImageMaskView *baseImage;
圖片的有兩層婿崭,第一層為上面的覆蓋層_baseImage,第二層為刮刮樂刮開后顯示的圖片層beforeImage:
UIImageView *beforeImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image"]];
beforeImage.frame = CGRectMake(10, 60, self.view.frame.size.width-20, 100);
beforeImage.center = self.view.center;
[self.view addSubview:beforeImage];
beforeImage.layer.borderColor = [UIColor grayColor].CGColor;
beforeImage.layer.borderWidth = 1;
//創(chuàng)建ImageMaskView
_baseImage = [[ImageMaskView alloc] initWithImage:[UIImage imageNamed:@"base"]];
_baseImage.alpha = 1.0;
_baseImage.frame = CGRectMake(10, 60, self.view.frame.size.width-20, 100);
_baseImage.center = self.view.center;
[self.view addSubview:_baseImage];
實(shí)現(xiàn)基本UI后,設(shè)置畫筆半徑radius大小:
//設(shè)置畫筆的半徑
_baseImage.radius = 10;
調(diào)用ImageMaskView的beginInteraction方法:
// Initialization code
self.userInteractionEnabled = YES;
self.backgroundColor = [UIColor clearColor];
self.imageMaskFilledDelegate = self.imageMaskFilledDelegate ? self.imageMaskFilledDelegate : nil;
self.radius = self.radius > 0 ? self.radius : 20;
// Initalize bitmap context
CGSize size = self.image.size;
self.colorSpace = CGColorSpaceCreateDeviceRGB();
self.imageContext = CGBitmapContextCreate(0,size.width,
size.height,
8,
size.width*4,
colorSpace,
kCGImageAlphaPremultipliedLast );
CGContextDrawImage(self.imageContext, CGRectMake(0, 0, size.width, size.height), self.image.CGImage);
int blendMode = kCGBlendModeClear;
CGContextSetBlendMode(self.imageContext, (CGBlendMode) blendMode);
tilesX = size.width / (2 * self.radius);
tilesY = size.height / (2 * self.radius);
self.maskedMatrix = [[Matrix alloc] initWithMax:MySizeMake(tilesX, tilesY)];
self.tilesFilled = 0;
最重要的是要要設(shè)置代理:
_baseImage.imageMaskFilledDelegate = self;
實(shí)現(xiàn)代理方法:
#pragma mark ImageMaskFilledDelegate
- (void) imageMaskView:(ImageMaskView *)maskView clearPercentDidChanged:(float)clearPercent{
if (clearPercent > 50) {
[UIView animateWithDuration:2
animations:^{
_baseImage.userInteractionEnabled = NO;
_baseImage.alpha = 0;
_baseImage.imageMaskFilledDelegate = nil;
}
completion:^(BOOL finished) {
}];
}
}
效果圖:
GIF圖片:
需要源碼的蝙场,點(diǎn)擊這里