美文网首页
iOS 图片裁剪

iOS 图片裁剪

作者: 清水_yuxin | 来源:发表于2021-02-07 18:04 被阅读0次
    typedef void(^ImageCropCompleteBlock)(UIImage *);
    @interface YXTestController : UIViewController
    
    @property (nonatomic, strong) UIImage * originalImage;
    @property (nonatomic, copy) ImageCropCompleteBlock complete;
    
    @end
    
    #import "YXTestController.h"
    
    @interface YXTestController ()
    @property (nonatomic, strong) UIImageView * imageView;
    @property (nonatomic, strong) UIView * maskView;
    @property (nonatomic, assign) CGRect cutRect;
    
    @property (nonatomic, assign) CGSize imageMinSize;
    @property (nonatomic, assign) BOOL isWideImg;
    @end
    
    @implementation YXTestController {
        CGFloat _viewWeidth;
        CGFloat _viewHeight;
        CGFloat _animationTime;
        CGFloat _maxScale;          // 图片最大放大倍数
    
        CGFloat _cutWidth;          // 裁剪宽高
        CGFloat _cutBordWidth;      // 裁剪边框宽度
        CGFloat _cutCornerRadius;   //裁剪边框圆角
        UIColor *_cutBordColor;     // 裁剪边框颜色
        UIColor *_cutMaskColor;     // 裁剪遮罩颜色
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        _cutCornerRadius = 6;
        _cutBordWidth = 3;
        _cutBordColor = [UIColor whiteColor];
        _cutMaskColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
        _maxScale = 5;
        _animationTime = 0.3f;
        _cutWidth = 300;
    
        _viewWeidth = self.view.frame.size.width;
        _viewHeight = self.view.frame.size.height;
        self.view.backgroundColor = [UIColor blackColor];
    
        [self setupImageView];
        [self addGestureRecognizer];
        [self addmaskView];
        [self addSubBttons];
    }
    
    #pragma mark - setup ui
    - (void)setupImageView{
    
        _imageView = [[UIImageView alloc]initWithImage:self.originalImage];
        [self.view addSubview:_imageView];
        _imageView.center = self.view.center;
    
        CGFloat weidthScale = _imageView.image.size.width / _viewWeidth;
        CGFloat heightScale = _imageView.image.size.height / _viewHeight;
    
        // 长宽按照比例显示
        CGFloat imgMixW = _cutWidth;
        CGFloat imgMixH = _cutWidth / (_imageView.image.size.width / _imageView.image.size.height);
        _isWideImg = NO;
        if (weidthScale > heightScale) {
            imgMixW = _cutWidth / (_imageView.image.size.height / _imageView.image.size.width);
            imgMixH = _cutWidth;
            _isWideImg = YES;
        }
        _imageView.bounds = CGRectMake(0, 0, imgMixW, imgMixH);
        _imageMinSize = CGSizeMake(imgMixW, imgMixH);
    
    }
    - (void)addGestureRecognizer {
    
        UIPinchGestureRecognizer * pich = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pichGestureAction:)];
        [self.view addGestureRecognizer:pich];
    
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGestureAction:)];
        [self.view addGestureRecognizer:pan];
    }
    
    - (void)addmaskView {
    
        CGFloat maskX = (_viewWeidth - _cutWidth)/2.0;
        CGFloat maskY = (_viewHeight - _cutWidth)/2.0;
        CGRect maskRect = CGRectMake(maskX, maskY, _cutWidth, _cutWidth);
        _cutRect = maskRect;
    
        //描边
        CAShapeLayer *borderLayer = [CAShapeLayer layer];
        borderLayer.frame = self.view.bounds;
        borderLayer.lineWidth = _cutBordWidth;
        borderLayer.strokeColor = _cutBordColor.CGColor;
        borderLayer.fillColor = [UIColor clearColor].CGColor;
        
        UIBezierPath *bezierPath=[UIBezierPath bezierPathWithRoundedRect:maskRect
                                                            cornerRadius:_cutCornerRadius];
        borderLayer.path = bezierPath.CGPath;
    
        self.maskView = [UIView new];
        self.maskView.backgroundColor = [UIColor clearColor];
        self.maskView.frame = self.view.bounds;
        [self.view addSubview:self.maskView];
    
        [self.maskView.layer insertSublayer:borderLayer atIndex:0];
    
    
        {//镂空
            CAShapeLayer *maskLayer = [CAShapeLayer layer];
            maskLayer.frame = self.view.bounds;
            maskLayer.fillColor = _cutMaskColor.CGColor;
    
            UIBezierPath *bezierPath=[UIBezierPath bezierPathWithRect:self.view.bounds];
            [bezierPath appendPath:[[UIBezierPath bezierPathWithRoundedRect:maskRect cornerRadius:_cutCornerRadius] bezierPathByReversingPath]];
            maskLayer.path = bezierPath.CGPath;
    
            [self.maskView.layer insertSublayer:maskLayer atIndex:0];
        }
    }
    
    - (void)addSubBttons{
    
        UIButton * cancleButton = [[UIButton alloc]init];
        [self.view addSubview:cancleButton];
        [cancleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancleButton setTitle:@"取消" forState:UIControlStateNormal];
        cancleButton.frame = CGRectMake(30, _viewHeight-60, 40, 40);
        [cancleButton addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
        UIButton * tureButton = [[UIButton alloc]init];
        [self.view addSubview:tureButton];
        [tureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [tureButton setTitle:@"确定" forState:UIControlStateNormal];
        tureButton.frame = CGRectMake(_viewWeidth -70, _viewHeight-60, 40, 40);
        [tureButton addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    }
    
    #pragma mark - action
    - (void)cancelBtnClick {
        [self.navigationController popViewControllerAnimated:YES];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    - (void)sureBtnClick {
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(_cutWidth, _cutWidth), YES, [UIScreen mainScreen].scale);
    
        CGFloat imgX = _imageView.frame.origin.x-(_viewWeidth-_cutWidth)/2;
        CGFloat imgY = _imageView.frame.origin.y - (_viewHeight-_cutWidth)/2;
        CGFloat imgW = _imageView.frame.size.width;
        CGFloat imgH = _imageView.frame.size.height;
    
        [_imageView.image drawInRect:CGRectMake(imgX, imgY, imgW, imgH)];
        UIImage * tempImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        if (self.complete) {
            self.complete(tempImage);
        }
    
        [self.navigationController popViewControllerAnimated:YES];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    // 手势
    - (void)pichGestureAction:(UIPinchGestureRecognizer *)pinch{
    
        if (pinch.state == UIGestureRecognizerStateBegan || pinch.state == UIGestureRecognizerStateChanged) {
            CGFloat newWidth = _imageView.frame.size.width * pinch.scale;
            CGFloat newHeight = _imageView.frame.size.height * pinch.scale;
            _imageView.bounds = CGRectMake(0, 0, newWidth, newHeight);
            pinch.scale = 1;
        }else if(pinch.state == UIGestureRecognizerStateEnded){
    
            [self autoScale];
    
            [self autoTransLationUseRect:_imageView.frame];
        }
    }
    
    - (void)panGestureAction:(UIPanGestureRecognizer *)pan{
    
        if (pan.state == UIGestureRecognizerStateBegan || pan.state == UIGestureRecognizerStateChanged) {
    
            CGPoint transLationPoint = [pan translationInView:self.view];
            CGFloat newCentX = _imageView.center.x + transLationPoint.x;
            CGFloat newCentY = _imageView.center.y + transLationPoint.y;
            _imageView.center = CGPointMake(newCentX, newCentY);
    
            [pan setTranslation:CGPointZero inView:self.view.superview];
    
        }else if(pan.state == UIGestureRecognizerStateEnded){
    
            [self autoTransLationUseRect:_imageView.frame];
        }
    }
    
    // 移动处理
    - (void)autoTransLationUseRect:(CGRect)imgFrame {
    
        CGRect cutRect = self.cutRect;
        // 水平方向
        if (imgFrame.origin.x > cutRect.origin.x) { //左边
            imgFrame.origin.x = cutRect.origin.x;
        }
    
        if (CGRectGetMaxX(imgFrame) <= CGRectGetMaxX(cutRect)) {   //右边
            imgFrame.origin.x  = CGRectGetMaxX(cutRect) - imgFrame.size.width;
        }
    
        // 垂直方向
        if (imgFrame.origin.y > cutRect.origin.y) {
            imgFrame.origin.y = cutRect.origin.y;
        }
        if (CGRectGetMaxY(imgFrame) <= CGRectGetMaxY(cutRect)) {
            imgFrame.origin.y = CGRectGetMaxY(cutRect) - imgFrame.size.height;
        }
    
        if (imgFrame.size.width < cutRect.size.width || imgFrame.size.height < cutRect.size.height) {
            CGPoint center = CGPointMake(cutRect.origin.x+_cutWidth/2, cutRect.origin.y+_cutWidth/2);
            [UIView animateWithDuration:_animationTime animations:^{
                self.imageView.center = center;
            }];
        }else {
            [UIView animateWithDuration:_animationTime animations:^{
                self.imageView.frame = imgFrame;
            }];
        }
    
    }
    
    // 缩放处理,设置了边界。保证内容都在裁剪框里面
    - (void)autoScale {
        CGFloat scale = _imageView.frame.size.width / _cutWidth;
        if (_isWideImg) {
            scale = _imageView.frame.size.height / _cutWidth;
        }
        CGFloat imgW = _imageMinSize.width;
        CGFloat imgH = _imageMinSize.height;
        if (scale < 1) {
            [UIView animateWithDuration:_animationTime animations:^{
                self.imageView.bounds = CGRectMake(0, 0,imgW, imgH);
            }];
        }else if(scale > _maxScale){
            imgW = imgW * _maxScale;
            imgH = imgH * _maxScale;
            [UIView animateWithDuration:_animationTime animations:^{
                self.imageView.bounds = CGRectMake(0, 0,imgW, imgH);
            }];
        }
    }
    @end
    

    相关文章

      网友评论

          本文标题:iOS 图片裁剪

          本文链接:https://www.haomeiwen.com/subject/wwnztltx.html