### 仿微信 頭像截取

#import <UIKit/UIKit.h>
@class AvatorImageViewController;

@protocol AvatorImageViewControllerDelegate <NSObject>
- (void)avatorImageViewControllerDidCancel:(AvatorImageViewController *)controller;
- (void)avatorImageViewController:(AvatorImageViewController *)controller didFinishPickingImage:(UIImage *)image;
@end

@interface AvatorImageViewController : UIViewController
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, weak) id<AvatorImageViewControllerDelegate> delegate;
@end
#import "AvatorImageViewController.h"

static CGFloat viewW;
static CGFloat viewH;
static CGFloat newImageW;
static CGFloat newImageH;
static const CGFloat animationTime =  0.3f;
static CGFloat maxScale;

@interface AvatorImageViewController ()
/*! 圖片 */
@property (nonatomic, strong) UIImageView *imageView;
/*! 邊框 */
@property (nonatomic, strong) UIView *borderView;
/*! 圖片舊frame */
@property (nonatomic, assign) CGRect imageViewOldRect;
@end

@implementation AvatorImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    viewW = self.view.frame.size.width;
    viewH = self.view.frame.size.height;
    
    /*! 初始化圖片 */
    [self setupImage];
    /*! 初始化手勢 */
    [self setupGesture];
    /*! 初始化遮罩層 */
    [self setupMaskView];
    /*! 初始化按鈕 */
    [self setupButtons];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 初始化

- (void)setupImage{
    self.imageView = [[UIImageView alloc] initWithImage:self.image];
    self.imageView.center = self.view.center;
    [self.view addSubview:self.imageView];
    
    newImageW = kScreenW;
    newImageH = self.image.size.height / (self.image.size.width / kScreenW);
    self.imageView.bounds = CGRectMake(0, 0, newImageW, newImageH);
    self.imageViewOldRect = self.imageView.frame;
}

- (void)setupGesture{
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAvatorImage:)];
    [self.view addGestureRecognizer:pan];
    
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAvatorImage:)];
    [self.view addGestureRecognizer:pinch];
}

- (void)setupMaskView{
    UIView *maskView = [[UIView alloc] init];
    maskView.backgroundColor = [UIColor blackColor];
    maskView.alpha = 0.6;
    maskView.frame = self.view.bounds;
    [self.view addSubview:maskView];
    
    //遮罩
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, CGRectMake(0, 0, viewW, (viewH-viewW)*0.5));
    CGPathAddRect(path, nil, CGRectMake(0, (viewH-viewW)*0.5+viewW, viewW, (viewH-viewW)*0.5));
    maskLayer.path = path;
    maskView.layer.mask = maskLayer;
    
    //框
    self.borderView = [[UIView alloc] init];
    self.borderView.backgroundColor = [UIColor clearColor];
    self.borderView.layer.borderWidth = 1;
    self.borderView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.borderView.frame = CGRectMake(0, (viewH-viewW)*0.5, viewW, viewW);
    [self.view addSubview:self.borderView];
}

- (void)setupButtons{

    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(20, kScreenH - 50, 60, 25);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];

    UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    selectBtn.frame = CGRectMake(kScreenW-60-20, kScreenH-50, 60, 25);
    [selectBtn setTitle:@"選取" forState:UIControlStateNormal];
    [selectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [selectBtn addTarget:self action:@selector(selectBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:selectBtn];
    
}

#pragma mark - 按鈕
- (void)cancelBtnDidClick:(UIButton *)btn{
    self.imageView.frame = self.imageViewOldRect;
    
    if ([self.delegate respondsToSelector:@selector(avatorImageViewControllerDidCancel:)]) {
        [self.delegate avatorImageViewControllerDidCancel:self];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)selectBtnDidClick:(UIButton *)btn{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(viewW, viewW), YES, [UIScreen mainScreen].scale);
        // 這時(shí)候的imagerect要相對這個(gè)上下文了
        // y:減掉(viewH-viewW)/2是因?yàn)镃GSizeMake(viewW, viewW) 高度為viewW
        CGRect imageRect = CGRectMake(self.imageView.frame.origin.x, self.imageView.frame.origin.y - (viewH-viewW)/2, self.imageView.frame.size.width, self.imageView.frame.size.height);
        
        [self.imageView.image drawInRect:imageRect];
        UIImage * tempImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 不做這處理放大很多的情況下會(huì)有bug
            self.imageView.frame = self.imageViewOldRect;
            
            if ([self.delegate respondsToSelector:@selector(avatorImageViewController:didFinishPickingImage:)]) {
                [self.delegate avatorImageViewController:self didFinishPickingImage:tempImage];
            }
            
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    });
}

#pragma mark - 手勢
- (void)panAvatorImage:(UIPanGestureRecognizer *)gesture{
    if (gesture.state == UIGestureRecognizerStateBegan || gesture.state == UIGestureRecognizerStateChanged) {
        CGPoint transLationPoint = [gesture translationInView:self.view];
        CGFloat newCentX = self.imageView.center.x + transLationPoint.x;
        CGFloat newCentY = self.imageView.center.y + transLationPoint.y;
        self.imageView.center = CGPointMake(newCentX, newCentY);
        [gesture setTranslation:CGPointZero inView:self.view.superview];
    }else if (gesture.state == UIGestureRecognizerStateEnded) {
        [self translateAnimation];
    }
}

- (void)pinchAvatorImage:(UIPinchGestureRecognizer *)gesture{
    if (gesture.state == UIGestureRecognizerStateBegan || gesture.state == UIGestureRecognizerStateChanged) {
        CGFloat newWidth  = self.imageView.frame.size.width * gesture.scale;
        CGFloat newHeight = self.imageView.frame.size.height * gesture.scale;
        self.imageView.bounds = CGRectMake(0, 0, newWidth, newHeight);
        gesture.scale = 1;
    }else if (gesture.state == UIGestureRecognizerStateEnded) {
        // 處理縮放(超過縮放范圍則觸發(fā)彈簧效果)
        [self scaleAnimation];
        // 處理移動(dòng)(超過邊緣則觸發(fā)彈簧效果)
        [self translateAnimation];
    }
}

- (void)scaleAnimation{
    CGFloat scale = self.imageView.frame.size.width/viewW;
    maxScale = 1.5 + self.image.size.width/kScreenW<1?1:self.image.size.width/kScreenW/2;
    // 縮放比例大于最大比例或者小于最小比例則回到對應(yīng)比例
    if (scale < 1) {
        [UIView animateWithDuration:animationTime animations:^{
            self.imageView.bounds = CGRectMake(0, 0, newImageW, newImageH);
        }];
    }else if (scale > maxScale) {
        [UIView animateWithDuration:animationTime animations:^{
            self.imageView.bounds = CGRectMake(0, 0, newImageW * maxScale, newImageH * maxScale);
        }];
    }
}

- (void)translateAnimation{
    CGRect borderRect = self.borderView.frame;
    CGRect imageRect  = self.imageView.frame;
    
    //水平方向
    if (imageRect.origin.x > borderRect.origin.x) {
        imageRect.origin.x = borderRect.origin.x;
    }
    if (CGRectGetMaxX(imageRect) < CGRectGetMaxX(borderRect)) {
        imageRect.origin.x = CGRectGetMaxX(borderRect) - imageRect.size.width;
    }
    
    //垂直方向
    if (imageRect.origin.y > borderRect.origin.y) {
        imageRect.origin.y = borderRect.origin.y;
    }
    if (CGRectGetMaxY(imageRect) < CGRectGetMaxY(borderRect)) {
        imageRect.origin.y = CGRectGetMaxY(borderRect) - imageRect.size.height;
    }
    
    //寬度高度
    if (imageRect.size.width < borderRect.size.width || imageRect.size.height < borderRect.size.height){
        [UIView animateWithDuration:animationTime animations:^{
            self.imageView.center = self.borderView.center;
        }];
    }
    else{
        [UIView animateWithDuration:animationTime animations:^{
            self.imageView.frame = imageRect;
        }];
    }
    
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末两芳,一起剝皮案震驚了整個(gè)濱河市承粤,隨后出現(xiàn)的幾起案子篷就,更是在濱河造成了極大的恐慌看政,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瞄勾,死亡現(xiàn)場離奇詭異塘揣,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)憋他,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門孩饼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人竹挡,你說我怎么就攤上這事镀娶。” “怎么了此迅?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵汽畴,是天一觀的道長旧巾。 經(jīng)常有香客問我,道長忍些,這世上最難降的妖魔是什么鲁猩? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮罢坝,結(jié)果婚禮上廓握,老公的妹妹穿的比我還像新娘。我一直安慰自己嘁酿,他們只是感情好隙券,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著闹司,像睡著了一般娱仔。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上游桩,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天牲迫,我揣著相機(jī)與錄音,去河邊找鬼借卧。 笑死盹憎,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的铐刘。 我是一名探鬼主播陪每,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼镰吵!你這毒婦竟也來了檩禾?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤捡遍,失蹤者是張志新(化名)和其女友劉穎锌订,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體画株,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡辆飘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了谓传。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蜈项。...
    茶點(diǎn)故事閱讀 39,902評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖续挟,靈堂內(nèi)的尸體忽然破棺而出紧卒,到底是詐尸還是另有隱情,我是刑警寧澤诗祸,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布跑芳,位于F島的核電站轴总,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏博个。R本人自食惡果不足惜怀樟,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望盆佣。 院中可真熱鬧往堡,春花似錦、人聲如沸共耍。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽痹兜。三九已至穆咐,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間佃蚜,已是汗流浹背庸娱。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留谐算,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓归露,卻偏偏與公主長得像洲脂,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子剧包,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評論 2 354

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