- 业务逻辑:为需要切图的view添加pan手势,定义一个需要截取范围视图的成员属性,定义一个成员变量用来记录手指的开始点,在pan方法中,根据手势的状态,获取矩形框的开始起点和结束点,然后根据起点和终点,获取截取范围,然后开启位图上下文,设置裁剪区域,把内容渲染到上下文,获取新的图片,结束上下文,最后删除截取范围视图,并值为nil,移除手势
@interface ViewController ()
// 开始起点属性
@property (nonatomic, assign) CGPoint startP;
// 截取范围视图
@property (nonatomic, weak) UIView *clipView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
- (UIView *)clipView
{
if (!_clipView) {
UIView *clipView = [[UIView alloc] init];
clipView.backgroundColor = [UIColor blackColor];
clipView.alpha = 0.5;
_clipView = clipView;
[self.view addSubview:_clipView];
}
return _clipView;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self addGesture];
}
- (void)addGesture
{
// 添加pan手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self.view addGestureRecognizer:pan];
}
#pragma mark - pan手势
- (void)pan:(UIPanGestureRecognizer *)pan
{
CGPoint endP = CGPointZero;
// 获取矩形框的开始起点
if (pan.state == UIGestureRecognizerStateBegan) {
// 获取一开始触摸点
self.startP = [pan locationInView:self.view];
}else if (pan.state == UIGestureRecognizerStateChanged)
{
// 获得结束那一时刻的点
endP = [pan locationInView:self.view];
// 根据起点和终点,获取截取范围
CGFloat w = endP.x - self.startP.x;
CGFloat h = endP.y - self.startP.y;
CGRect clipRect = CGRectMake(self.startP.x, self.startP.y, w, h);
self.clipView.frame = clipRect;
}else if (pan.state == UIGestureRecognizerStateEnded)
{
// 开启上下文
UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);
// 设置裁剪区域
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.clipView.frame];
[path addClip];
// 把内容渲染到上下文
[self.imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
// 获取新的图片
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
// 结束上下文
UIGraphicsEndImageContext();
// 删除clipView视图
[self.clipView removeFromSuperview];
self.clipView = nil;
[self.view removeGestureRecognizer:pan];
}
}