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