需要实现的效果:
当点击一张图片时,可以扩大到整个屏幕.再次点击时缩小到原来的大小
实现思路:
1.封装一个继承UIImageView的类,再定义一个imageview和scrollview的属性
2.再初始化方法中调用创建子视图的方法(记得给UIImageView打开用户交互),初始化scrollview和Imageview,并且把scrollview添加到self.window上,Imageview添加到scrollview上
3.给self和属性Imagevie 添加手势,两个手势方法控制图片的缩小和放大,图片放大是将scrollview的frame给属性imageview并隐藏self;图片缩小是将self的frame给属性image view并把self的hidden值设置为NO,scrollview也从父视图中移除,当点击self时可实现放大图片,当点击Imageview可实现还原图片.
代码实现:
#import <UIKit/UIKit.h>
@interface ZoomImgView : UIImageView
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UIImageView *imgView;
@end
#import "ZoomImgView.h"
@implementation ZoomImgView
-(instancetype)initWithFrame:(CGRect)frame{
if ([super initWithFrame:frame]) {
[self _inteTap];
}
return self;
}
- (void)_inteTap{
self.userInteractionEnabled = YES;
//添加手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBig)];
[self addGestureRecognizer:tap];
}
- (void)tapBig{
//弹出来的视图
[self creactSubView];
//放大的动画
[UIView animateWithDuration:.3 animations:^{
_imgView.frame = _scrollView.frame;
_scrollView.backgroundColor = [UIColor blackColor];
self.hidden = YES;
}];
}
- (void)creactSubView{
_scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
[self.window addSubview:_scrollView];
CGRect frame = [self convertRect:self.bounds toView:self.window];
_imgView = [[UIImageView alloc] initWithFrame:frame];
_imgView.image = self.image;
_imgView.userInteractionEnabled = YES;
//添加手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(smallTap)];
[_imgView addGestureRecognizer:tap];
[_scrollView addSubview:_imgView];
}
- (void)smallTap{
[UIView animateWithDuration:.3 animations:^{
_imgView.frame = self.frame;
} completion:^(BOOL finished) {
self.hidden = NO;
[_scrollView removeFromSuperview];
}];
}
@end
#import "ViewController.h"
#import "ZoomImgView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
ZoomImgView *imgView = [[ZoomImgView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
imgView.image = [UIImage imageNamed:@"nn.png"];
[self.view addSubview:imgView];
}
@end
![Uploading 图片放大_952149.gif . . .]