3. 选择裁剪区域,进行图片裁剪

  1. 头文件
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface ZQImageView : UIImageView

@end

NS_ASSUME_NONNULL_END
  1. 具体文件

#import "ZQImageView.h"


@interface ZQImageView ()
@property (nonatomic, assign) CGPoint beginPoint;
@property (nonatomic, strong) UIView *clipView;
@end

@implementation ZQImageView


- (UIView *)clipView{
    if(_clipView==nil){
        _clipView = [[UIView alloc]init];
        _clipView.backgroundColor = [UIColor grayColor];
        _clipView.alpha = 0.7;
        [[self superview] addSubview:_clipView];
    }
    return _clipView;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame: frame]){
        self.userInteractionEnabled = YES;
        UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(gestureRecognizer:)];
        [self addGestureRecognizer:gestureRecognizer];
    }
    return self;
}

-(void)gestureRecognizer:(UIPanGestureRecognizer*)pan{
    CGPoint cur = [pan locationInView:self];
    if(pan.state == UIGestureRecognizerStateBegan){
        self.beginPoint  = cur;
    }
    if(pan.state == UIGestureRecognizerStateChanged){
        CGFloat x =  self.beginPoint.x;
        CGFloat y = self.beginPoint.y;
        CGFloat w = cur.x  - self.beginPoint.x;
        CGFloat H = cur.y - self.beginPoint.y;
        self.clipView.frame = CGRectMake(x, y, w, H);
        
    }
    if(pan.state == UIGestureRecognizerStateEnded){
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
        UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.clipView.frame];
        [path addClip];
        CGContextRef ctx =  UIGraphicsGetCurrentContext();
        [self.layer renderInContext:ctx];
        UIImage *newImage =  UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        self.image = newImage;
        [self.clipView removeFromSuperview];
        self.clipView = nil;
    }
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容