1、首先在storyboard中拖两个imageView,是相互重叠的两个imageView,把要刮开显示的图片放到下面,上面的imageView显示要刮掉的图片,在上层显示的图片要开启交互功能,如图:
2、代码实现。
上层的imageView拖到控制器一个属性,同时再建立一个属性判断手指是否在触摸屏幕;
@property(nonatomic,assign) BOOL isTouch;
@property (weak, nonatomic) IBOutlet UIImageView *imageB;
获取手指并判断手指是否在触摸
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ // 获取手指 UITouch *touch = [touches anyObject]; // 判断手指是否在触摸 if (touch.view == self.imageB ) { self.isTouch = YES; } }
获取到手指滑动的位置,把滑动的位置成为透明状态,就显示出底部的图片,从而造成是刮开上面的视图,露出底部视图的效果
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { if (self.isTouch) { // 开启上下文 UIGraphicsBeginImageContext(self.imageB.frame.size); // 将图片绘制到图形上下文中 [self.imageB.image drawInRect:self.imageB.bounds]; // 清空手指触摸的位置 // 拿到手指,根据手指的位置,让对应的位置成为透明 UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:touch.view]; CGRect rect = CGRectMake(point.x - 10, point.y - 10, 20, 20); // 清空rect CGContextClearRect(UIGraphicsGetCurrentContext(), rect); // 取出会之后的图片赋值给imageB self.imageB.image = UIGraphicsGetImageFromCurrentImageContext(); // 关闭图形上下文 UIGraphicsEndImageContext(); } }
手指离开屏幕时,判断
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ self.isTouch = NO; }