iOS 圖片裁剪

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;          // 圖片最大放大倍數(shù)

    CGFloat _cutWidth;          // 裁剪寬高
    CGFloat _cutBordWidth;      // 裁剪邊框?qū)挾?    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;

    // 長(zhǎng)寬按照比例顯示
    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];
}
// 手勢(shì)
- (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];
    }
}

// 移動(dòng)處理
- (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;
        }];
    }

}

// 縮放處理,設(shè)置了邊界混卵。保證內(nèi)容都在裁剪框里面
- (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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子签舞,更是在濱河造成了極大的恐慌绢陌,老刑警劉巖扑媚,帶你破解...
    沈念sama閱讀 216,470評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件曾我,死亡現(xiàn)場(chǎng)離奇詭異勤家,居然都是意外死亡圾浅,警方通過(guò)查閱死者的電腦和手機(jī)掠手,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)贱傀,“玉大人惨撇,你說(shuō)我怎么就攤上這事「” “怎么了魁衙?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,577評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵报腔,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我剖淀,道長(zhǎng)纯蛾,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,176評(píng)論 1 292
  • 正文 為了忘掉前任纵隔,我火速辦了婚禮翻诉,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘捌刮。我一直安慰自己碰煌,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,189評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布绅作。 她就那樣靜靜地躺著芦圾,像睡著了一般。 火紅的嫁衣襯著肌膚如雪俄认。 梳的紋絲不亂的頭發(fā)上个少,一...
    開(kāi)封第一講書(shū)人閱讀 51,155評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音眯杏,去河邊找鬼夜焦。 笑死,一個(gè)胖子當(dāng)著我的面吹牛岂贩,可吹牛的內(nèi)容都是我干的茫经。 我是一名探鬼主播,決...
    沈念sama閱讀 40,041評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼河闰,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼科平!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起姜性,我...
    開(kāi)封第一講書(shū)人閱讀 38,903評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤瞪慧,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后部念,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體弃酌,經(jīng)...
    沈念sama閱讀 45,319評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,539評(píng)論 2 332
  • 正文 我和宋清朗相戀三年儡炼,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了妓湘。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,703評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡乌询,死狀恐怖榜贴,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情妹田,我是刑警寧澤唬党,帶...
    沈念sama閱讀 35,417評(píng)論 5 343
  • 正文 年R本政府宣布鹃共,位于F島的核電站,受9級(jí)特大地震影響驶拱,放射性物質(zhì)發(fā)生泄漏霜浴。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,013評(píng)論 3 325
  • 文/蒙蒙 一蓝纲、第九天 我趴在偏房一處隱蔽的房頂上張望阴孟。 院中可真熱鬧,春花似錦税迷、人聲如沸永丝。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,664評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)类溢。三九已至凌蔬,卻和暖如春露懒,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背砂心。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,818評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工懈词, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人辩诞。 一個(gè)月前我還...
    沈念sama閱讀 47,711評(píng)論 2 368
  • 正文 我出身青樓坎弯,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親译暂。 傳聞我的和親對(duì)象是個(gè)殘疾皇子抠忘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,601評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容