释放双眼,带上耳机,听听看~!
- 废话不多说,直接上代码
#import "ImgeController.h"
@interface ImgeController ()
@property (nonatomic, strong) UIImageView *ivCover;
@end
@implementation ImgeController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor blackColor];
UIImageView *ivB = [[UIImageView alloc]initWithFrame:self.view.bounds];
ivB.backgroundColor = [UIColor orangeColor];
[self.view addSubview:ivB];
_ivCover = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 400, 400)];
_ivCover.contentMode = UIViewContentModeScaleAspectFit;
_ivCover.image = [UIImage imageNamed:@"linshitupian"];
_ivCover.center = self.view.center;
_ivCover.userInteractionEnabled = YES;
[self.view addSubview:_ivCover];
//添加手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self.view addGestureRecognizer:pan];
}
- (void)pan:(UIPanGestureRecognizer *)pan{
//获取手指在擦除view上的点
CGPoint curP = [pan locationInView:self.ivCover];
/*
确定擦除区域.
假设擦除区域的宽高为30.
那点当前的擦除范围应该是通过当前的手指所在的点来确定擦除的范围,位置.
那么当前擦除区域的x应该是等于当前手指的x减去擦除范围的一半,同样,y也是当前手指的y减去高度的一半.
*/
CGFloat rectWH = 30;
CGFloat x = curP.x - rectWH * 0.5;
CGFloat y = curP.y - rectWH * 0.5;
//确定擦除的位置尺寸.
CGRect rect = CGRectMake(x, y, rectWH, rectWH);
//开启位图上下文.
UIGraphicsBeginImageContextWithOptions(self.ivCover.bounds.size, NO, 0);
//获取当前的上下文.
CGContextRef ctx = UIGraphicsGetCurrentContext();
//把ivCover上的图片渲染到上下文中.
[self.ivCover.layer renderInContext: ctx];
//设置擦除区域
CGContextClearRect(ctx, rect);
//生成一张新的图片.
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//关闭位图上下文.
UIGraphicsEndImageContext();
//给图片重新赋值
self.ivCover.image = newImage;
}
@end