在网上看到一个不错的封装,导入代码直接可以使用,废话不多说直接上代码:
.h文件
#import <Foundation/Foundation.h>
@interface SJAvatarBrowser : NSObject
+(void)showImage:(UIImageView*)avatarImageView;
@end
.m文件
#import "SJAvatarBrowser.h"
static CGRect oldframe;
@implementation SJAvatarBrowser
+(void)showImage:(UIImageView *)avatarImageView{
UIImage *image=avatarImageView.image;
UIWindow *window=[UIApplication sharedApplication].keyWindow;
UIView *backgroundView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
oldframe=[avatarImageView convertRect:avatarImageView.bounds toView:window];
backgroundView.backgroundColor=[UIColor blackColor];
backgroundView.alpha=0;
UIImageView *imageView=[[UIImageView alloc]initWithFrame:oldframe];
imageView.image=image;
imageView.tag=1;
[backgroundView addSubview:imageView];
[window addSubview:backgroundView];
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImage:)];
[backgroundView addGestureRecognizer: tap];
[UIView animateWithDuration:0.3 animations:^{
imageView.frame=CGRectMake(0,([UIScreen mainScreen].bounds.size.height-image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width)/2, [UIScreen mainScreen].bounds.size.width, image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width);
backgroundView.alpha=1;
} completion:^(BOOL finished) {
}];
}
+(void)hideImage:(UITapGestureRecognizer*)tap{
UIView *backgroundView=tap.view;
UIImageView *imageView=(UIImageView*)[tap.view viewWithTag:1];
[UIView animateWithDuration:0.3 animations:^{
imageView.frame=oldframe;
backgroundView.alpha=0;
} completion:^(BOOL finished) {
[backgroundView removeFromSuperview];
}];
}
@end
单张图片:
直接添加tap手势,调用方法
[SJAvatarBrowser showImage:self.imageView];
多张图片:
如果图片不止一张,则:
//允许交互
_imageView.userInteractionEnabled = YES;
//添加手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
[_imageView addGestureRecognizer:tap];
调用方法:
-(void)tapAction:(UITapGestureRecognizer *)tap
{
[SJAvatarBrowser showImage:(UIImageView *)tap.view];
}
附github地址: https://github.com/tangwei6423471/SJAvatarBrowser