iOS 图片擦除
2016-01-22 本文已影响705人
smirkk
- 业务逻辑:上下两张图片,上方的图片遮盖下方的图片,为上方图片添加手势,根据手势的位置创建一个擦除的小块,然后开启位图,渲染被擦除的图层,清除掉pan手势划过的区域,得到上下文的位图,最后关闭上下文,将新的图片赋值给被擦除的图片。
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self.view addGestureRecognizer:pan];
}
#define clipWH 30
- (void)pan:(UIPanGestureRecognizer *)pan
{
// 获取当前触摸点
CGPoint curP = [pan locationInView:self.view];
// 获取擦除的矩形范围
CGFloat wh = clipWH;
CGFloat x = curP.x - wh * 0.5;
CGFloat y = curP.y - wh * 0.5;
CGRect rect = CGRectMake(x, y, wh, wh);
// 开启位图上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
// 获取当前上下文
CGContextRef ctx = UIGraphicsGetCurrentContext(
// 渲染控件
[self.imageView.layer renderInContext:ctx];
// 擦除上下文的某一部分
CGContextClearRect(ctx, rect);
// 生成一张图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
self.imageView.image = image;
// 关闭上下文
UIGraphicsEndImageContext();
}