iOS 实现点击微信头像效果

公司产品需要实现点击个人主页头像可以放大头像、缩放头像、保存头像效果(和点击微信个人头像类似),故找个时间实现一下,记录下来,供自己查看,也给大家做个参考。

实现效果(GIF):

2017-03-08 09_42_20.gif

实现思路:

直接自定义 UIView(CYPhotoPreviewer),为了实现双击缩放,可以实现 UIScrollViewDelegate 对应的方法。如果需要模糊背景,可以在自定义的 UIView 中先添加模糊背景,再添加 UIScrollView,继而在 UIScrollView 中添加图片容器,这个容器就是要显示的图片的 superView,代码一目了然:

- (void)setup {
    
    self.frame = [UIScreen mainScreen].bounds;
    self.backgroundColor = [UIColor clearColor];
  
   UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    [self addGestureRecognizer:singleTap];
    
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
    doubleTap.numberOfTapsRequired = 2;
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [self addGestureRecognizer:doubleTap];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self addGestureRecognizer:longPress];
    
    // 设置模糊背景
    self.blurBackground = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
    self.blurBackground.frame = self.frame;
    [self addSubview:self.blurBackground];
    
    // 设置 UIScrollView 相关属性
    self.scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.scrollView.delegate = self;
    self.scrollView.bouncesZoom = YES;
    self.scrollView.maximumZoomScale = 3.0;
    self.scrollView.multipleTouchEnabled = YES;
    self.scrollView.alwaysBounceVertical = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self addSubview:self.scrollView];
    
    // containerView
    self.containerView = [[UIView alloc] init];
    [self.scrollView addSubview:self.containerView];
    
    // imageView
    self.imageView = [[UIImageView alloc] init];
    self.imageView.clipsToBounds = YES;
    self.imageView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5];
    [self.containerView addSubview:self.imageView];
}

可以看到,我们给设置了模糊背景,给这个 CYPhotoPreviewer 添加了单击手势(关闭 PhotoPreviewer)、双击手势(缩放图片)、长按手势(使用 UIAlertController 菜单,比如保存图片等)。

好,确定了这个 CYPhotoPreviewer 中的显示内容,那么我们该如何显示这个 CYPhotoPreviewer 呢?

  • 直接将这个 CYPhotoPreviewer 添加到 keyWindow 上
  • 将这个 CYPhotoPreviewer 添加到控制器的 self.view 上

这两种方式的实现都差不多,不过如果使用第一种方式的话,会导致将 CYPhotoPreviewer 添加到 keyWindow 上之后,再长按继续将 UIAlertController 显示就比较麻烦了,因此,这里打算采用将 CYPhotoPreviewer 添加到控制器的 self.view 上,继而就可以很方便的显示 UIAlertController 了:

- (void)previewFromImageView:(UIImageView *)fromImageView inContainer:(UIView *)container {
    _fromImageView = fromImageView;
    fromImageView.hidden = YES;
    [container addSubview:self]; // 将 CYPhotoPreviewer 添加到 container 上

    self.containerView.origin = CGPointZero;
    self.containerView.width = self.width; // containerView 的宽度是屏幕的宽度
    
    UIImage *image = fromImageView.image;
    
    // 计算 containerView 的高度
    if (image.size.height / image.size.height > self.height / self.width) {
        self.containerView.height = floor(image.size.height / (image.size.width / self.width));
    } else {
        CGFloat height = image.size.height / image.size.width * self.width;
        if (height < 1 || isnan(height)) height = self.height;
        height = floor(height);
        self.containerView.height = height;
        self.containerView.centerY = self.height / 2;
    }
    
    if (self.containerView.height > self.height && self.containerView.height - self.height <= 1) {
        self.containerView.height = self.height;
    }
    
    self.scrollView.contentSize = CGSizeMake(self.width, MAX(self.containerView.height, self.height));
    [self.scrollView scrollRectToVisible:self.bounds animated:NO];
    
    if (self.containerView.height <= self.height) {
        self.scrollView.alwaysBounceVertical = NO;
    } else {
        self.scrollView.alwaysBounceVertical = YES;
    }
    
    CGRect fromRect = [fromImageView convertRect:fromImageView.bounds toView:self.containerView];
    
    self.imageView.frame = fromRect;
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.imageView.image = image;
    
    [UIView animateWithDuration:0.18 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
        self.imageView.frame = self.containerView.bounds;
        self.imageView.transform = CGAffineTransformMakeScale(1.01, 1.01);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.18 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
            self.imageView.transform = CGAffineTransformMakeScale(1.00, 1.00);
        } completion:nil];
    }];
}

可以看到,我们将外面的图片 fromImageView 传递进来,是为了显示更好的动画效果;将控制器的 container(self.view)传递进来,是为了将 CYPhotoPreviewer 添加到 container 的细节不需要在调用处处理,即初始化 CYPhotoPreviewer 之后,CYPhotoPreviewer 就直接被 container 添加为 subview 了。动画很简单不再细说。

显示的效果已经做好,单击关闭 CYPhotoPreviewer 也比较好实现,只需要从父类移除 CYPhotoPreviewer 即可:

- (void)dismiss {
    [UIView animateWithDuration:0.18 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        CGRect fromRect = [self.fromImageView convertRect:self.fromImageView.bounds toView:self.containerView];
        self.imageView.contentMode = self.fromImageView.contentMode;
        self.imageView.frame = fromRect;
        self.blurBackground.alpha = 0.01;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.10 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.fromImageView.hidden = NO;
            self.alpha = 0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }];
}

好了,显示和关闭 CYPhotoPreviewer 都实现了,如果需要双击缩放图片效果,就得实现 UIScrollViewDelegate 的两个方法以及 CYPhotoPreviewer 的双击手势:

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.containerView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    UIView *subView = self.containerView;
    
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    
    subView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                 scrollView.contentSize.height * 0.5 + offsetY);
}

- (void)doubleTap:(UITapGestureRecognizer *)recognizer {
    if (self.scrollView.zoomScale > 1.0) {
        [self.scrollView setZoomScale:1.0 animated:YES];
    } else {
        CGPoint touchPoint = [recognizer locationInView:self.imageView];
        CGFloat newZoomScale = self.scrollView.maximumZoomScale;
        CGFloat xSize = self.width / newZoomScale;
        CGFloat ySize = self.height / newZoomScale;
        [self.scrollView zoomToRect:CGRectMake(touchPoint.x - xSize / 2, touchPoint.y - ySize / 2, xSize, ySize) animated:YES];
    }
}

最后一个就是长按弹出菜单(UIAlertController)了:

- (void)longPress:(UILongPressGestureRecognizer *)recognizer {
    
    // 为了避免弹警告:Warning: Attempt to present <UIAlertController: 0x7fcb1e619e80>  on <ViewController: 0x7fcb1e60f9f0> which is already presenting <UIAlertController: 0x7fcb1e50d2e0>,最好加入状态判断
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"QuoraDots" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        
        UIViewController *vc = self.viewController;
        [vc presentViewController:alertController animated:YES completion:nil];
    }
}

注意一点,longPress: 这个方法会调用很频繁,因此,为了避免 Attempt to present xxx on xxx which is already presenting xxx 这个警告,我们需要判断手势的状态。

后话:

这个只是显示单张图片的大图,如果需要显示多张图片类似微信微博的九宫格图片的大图显示,则需要将这个 CYPhotoPreviewer 搞成 UICollectionView 的 item 即可,大家可以尝试尝试。最后,如果需要或者 CYPhotoPreviewer 源码,可以前往 GitHub 下载查看:https://github.com/angelen10/PhotoPreviewer

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容