需要實現(xiàn)的效果:
當點擊一張圖片時,可以擴大到整個屏幕.再次點擊時縮小到原來的大小
實現(xiàn)思路:
1.封裝一個繼承UIImageView的類,再定義一個imageview和scrollview的屬性
2.再初始化方法中調用創(chuàng)建子視圖的方法(記得給UIImageView打開用戶交互),初始化scrollview和Imageview,并且把scrollview添加到self.window上,Imageview添加到scrollview上
3.給self和屬性Imagevie 添加手勢,兩個手勢方法控制圖片的縮小和放大,圖片放大是將scrollview的frame給屬性imageview并隱藏self;圖片縮小是將self的frame給屬性image view并把self的hidden值設置為NO,scrollview也從父視圖中移除,當點擊self時可實現(xiàn)放大圖片,當點擊Imageview可實現(xiàn)還原圖片.
代碼實現(xiàn):
#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 . . .]