#import "ViewController.h" @interface ViewController () //显示图片 @property (weak, nonatomic) IBOutlet UIImageView *imageView; //pan手指刚开始移动的位置 @property (nonatomic, assign) CGPoint startPoint; //pan手势结束的位置 @property (nonatomic, assign) CGPoint endPoint; //剪切的半透明视图 @property (nonatomic, strong) UIView *clipView; @end
@implementation ViewController //懒加载clipView,在拖拽的过程中只创建一次,避免视图上创建过多无用的view - (UIView*)clipView { if (_clipView == nil) { _clipView = [[UIView alloc] init]; _clipView.backgroundColor = [UIColor blackColor]; _clipView.alpha = 0.5; [self.view addSubview:_clipView]; } return _clipView; } - (void)viewDidLoad { [super viewDidLoad]; //给控制器添加一个pan手势 UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; [self.view addGestureRecognizer:panGesture]; } - (void)pan:(UIPanGestureRecognizer*)panGesture { if (panGesture.state == UIGestureRecognizerStateBegan) { //panBegin //startPoint保存pan手势的开始位置 CGPoint startPoint = [panGesture locationInView:self.view]; self.startPoint = startPoint; } else if (panGesture.state == UIGestureRecognizerStateChanged) { //PanChanged CGPoint endPoint = [panGesture locationInView:self.view]; self.endPoint = endPoint; CGFloat clipViewX = self.startPoint.x; CGFloat clipViewY = self.startPoint.y; CGFloat clipViewW = self.endPoint.x - self.startPoint.x; CGFloat clipCiewH = self.endPoint.y - self.startPoint.y; self.clipView.frame = CGRectMake(clipViewX, clipViewY, clipViewW, clipCiewH); } else if (panGesture.state == UIGestureRecognizerStateEnded) { //panEnded //图片裁剪,生成一张新的图片 //1.开启上下文 UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, NO, 0); //2.设置裁剪区域 UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.clipView.frame]; [path addClip]; //3.获取上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); //4.把控件上的内容渲染到上下文中 [self.imageView.layer renderInContext:ctx]; //5.生成一张新的图片 self.imageView.image = UIGraphicsGetImageFromCurrentImageContext(); //6.关闭就上下文 UIGraphicsEndImageContext(); //7.移除clipView [self.clipView removeFromSuperview]; } } @end
屏幕图片剪切效果演示:
时间: 2024-10-10 02:35:45