第一種方法:用捏合手勢放大縮小
代碼如下 復制代碼
@interfaceViewController ()
@property(strong, nonatomic) IBOutlet UIView *redView;
@property(assign, nonatomic) CGFloat scale;//記錄上次手勢結束的放大倍數
@property(assign, nonatomic) CGFloat realScale;//當前手勢應該放大的倍數
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchEvent:)];
[self.view addGestureRecognizer:pinchGesture];
self.scale =1;
}
- (void)pinchEvent:(UIPinchGestureRecognizer *)pinch {
self.realScale = self.scale + (pinch.scale -1);//當前的放大倍數是上次的放大倍數加上當前手勢pinch程度
if(self.realScale >10) {//設置最大放大倍數
self.realScale =10;
}elseif(self.realScale <0.5){//最小放大倍數
self.realScale =0.5;
}
self.redView.transform = CGAffineTransformMakeScale(self.realScale, self.realScale);
if(pinch.state == UIGestureRecognizerStateEnded){//當結束捏合手勢時記錄當前圖片放大倍數
self.scale = self.realScale;
}
NSLog(@"%f-------%f",self.scale,self.realScale);
}
@end
這種方式有個弊端:如果不進一步設置,放大的焦點只能是從中心開始,而且放大的部分超出屏幕不能滾動查看。
如果想用單擊雙擊手勢放大縮小用點擊手勢UITapGestureRecognizer就可以了,單擊設置屬性numberOfTapsRequired為1,雙擊設置為2,就可以了,實現他的點擊方法就可以了。
第二種方法:用scrollView的代理方法實現
設置放大倍數和代理
代碼如下 復制代碼
self.scrollView.minimumZoomScale =0.5;
self.scrollView.maximumZoomScale =10;
self.scrollView.delegate = self;
代理方法返回你要放大的圖片
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
returnself.enlargeImage;
}
在這個代理方法裡面設置滾動范圍、調整放大圖片的位置(如果不設置,放大後圖片按照原來比例frame的X,Y值也會跟隨比例變化,圖片就跑偏了)
代碼如下 復制代碼
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
CGRect frame = self.enlargeImage.frame;
frame.origin.y = (self.scrollView.frame.size.height - self.enlargeImage.frame.size.height) >0? (self.scrollView.frame.size.height - self.enlargeImage.frame.size.height) *0.5:0;
frame.origin.x = (self.scrollView.frame.size.width - self.enlargeImage.frame.size.width) >0? (self.scrollView.frame.size.width - self.enlargeImage.frame.size.width) *0.5:0;
self.enlargeImage.frame = frame;
self.scrollView.contentSize = CGSizeMake(self.enlargeImage.frame.size.width +30, self.enlargeImage.frame.size.height +30);
}