Quartz2D - 图片截取

来源:互联网 发布:dota2赌博软件 编辑:程序博客网 时间:2024/04/25 18:46
////  ViewController.m#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UIImageView *imageView;@property(nonatomic,assign)CGPoint startPoint;@property(nonatomic,weak)UIView *clipView;@end@implementation ViewController- (UIView *)clipView{    if (_clipView == nil) {        UIView *view = [[UIView alloc] init];        view.backgroundColor = [UIColor blackColor];        view.alpha = 0.5;        [self.view addSubview:view];                _clipView = view;    }    return _clipView;}- (void)viewDidLoad {    [super viewDidLoad];        // 给控制器的view添加一个pan手势    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];    [self.view addGestureRecognizer:pan]; }- (void)pan:(UIPanGestureRecognizer *)recognizer{    CGPoint endPoint = CGPointZero;        // 获取一开始的触摸点    if (recognizer.state == UIGestureRecognizerStateBegan) { // 一开始拖动的时候         self.startPoint = [recognizer locationInView:recognizer.view];    }else if (recognizer.state == UIGestureRecognizerStateChanged){ // 一直在拖动中        endPoint = [recognizer locationInView:recognizer.view];                CGFloat w = endPoint.x - self.startPoint.x;        CGFloat h = endPoint.y - self.startPoint.y;                // 获取截取范围        CGRect clipRect = CGRectMake(self.startPoint.x, self.startPoint.y, w, h);        self.clipView.frame = clipRect;    }else if (recognizer.state == UIGestureRecognizerStateEnded){ // 拖动结束               // 开启上下文        UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);        // 设置裁剪区域        UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.clipView.frame];        [path addClip];                // 获取上下文,渲染        CGContextRef ctx = UIGraphicsGetCurrentContext();        [self.imageView.layer renderInContext:ctx];                // 生成一张新的图片        self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();                // 关闭上下文        UIGraphicsEndImageContext();                // 移除遮罩的view        [self.clipView removeFromSuperview];        self.clipView = nil;    }   }@end

效果演示:


0 0
原创粉丝点击