注意2个图片要重叠。
//
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 添加pan手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self.view addGestureRecognizer:pan];
}
- (void)pan:(UIPanGestureRecognizer *)recognizer
{
// 获取当前触摸点
CGPoint currentPoint = [recognizer locationInView:recognizer.view];
// 设置擦除的笔头的大小
CGFloat wh = 30;
CGFloat x = currentPoint.x - wh * 0.5;
CGFloat y = currentPoint.y - wh * 0.5;
CGRect rect = CGRectMake(x, y, wh, wh);
// 开启图形上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 控件的layer渲染上去
[self.imageView.layer renderInContext:ctx];
// 擦除图片
CGContextClearRect(ctx, rect);
// 生成一张图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
self.imageView.image = image;
// 关闭上下文
UIGraphicsEndImageContext();
}
@end
效果演示: