1.加入Pan手势
判断Pan手势的三种状态 为begin状态的时候记录刚开始的触摸点
移动的时候添加一个半透明的黑色框
-(UIView *)clipView{
if (_clipView==nil) {
UIView*view=[[UIView alloc]init];
_clipView=view;
[self.view addSubview:view];
view.backgroundColor=[UIColor blackColor];
view.alpha=0.5;
}
return _clipView;
}
注意使用懒加载的方式
2.
在手移动的时候 改变view的frame
if (gesture.state==UIGestureRecognizerStateBegan) {
_beginPoint=[gesture locationInView:self.view];
}else if (gesture.state==UIGestureRecognizerStateChanged){
CGPoint currentP=[gesture locationInView:self.view];
CGFloat width=(currentP.x-_beginPoint.x);
CGFloat height=(currentP.y-_beginPoint.y);
CGRect rect=CGRectMake(_beginPoint.x, _beginPoint.y, width, height);
self.clipView.frame=rect;
}
3.结束的时候切割需要的上下文部分先创建位图上下文。然后切割需要的区域。然后把图片渲染上去,然后获取切割好的,最后关闭
//源码如下
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak,nonatomic)UIView*clipView;
@end
@implementation ViewController
{
CGPoint _beginPoint;
}
-(UIView *)clipView{
if (_clipView==nil) {
UIView*view=[[UIView alloc]init];
_clipView=view;
[self.view addSubview:view];
view.backgroundColor=[UIColor blackColor];
view.alpha=0.5;
}
return _clipView;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view addGestureRecognizer:[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panClick:)]];
}
//移动手势
-(void)panClick:(UIPanGestureRecognizer*)gesture{
if (gesture.state==UIGestureRecognizerStateBegan) {
_beginPoint=[gesture locationInView:self.view];
}else if (gesture.state==UIGestureRecognizerStateChanged){
CGPoint currentP=[gesture locationInView:self.view];
CGFloat width=(currentP.x-_beginPoint.x);
CGFloat height=(currentP.y-_beginPoint.y);
CGRect rect=CGRectMake(_beginPoint.x, _beginPoint.y, width, height);
self.clipView.frame=rect;
}else if (gesture.state==UIGestureRecognizerStateEnded){
//创建位图上下文
UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, NO, 0);
//创建切割区域
UIBezierPath*path=[UIBezierPath bezierPathWithRect:self.clipView.frame];
[path addClip];
CGContextRef context=UIGraphicsGetCurrentContext();
[self.imageView.layer renderInContext:context];
self.imageView.image=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.clipView removeFromSuperview];
//现在还可以打印出来,因为self.clipView在下一个runLoop的时候被销毁
NSLog(@"%@",self.clipView);
self.clipView=nil;
}
}