1.在.h檔案中加入一個變數用來記錄當前的scale值, 讓這個ViewController遵循
UIGestureRecognizerDelegate代理.
並在.h中加入下面這個變數
CGFloat lastScale;
2. 在viewDidLoad中加入下面語句
UIView *holderView = [[UIViewalloc]initWithFrame:CGRectMake(0,0,320,
416)];
UIImageView *showImgView = [[UIImageViewalloc]initWithFrame:CGRectMake(0,0,320,
416)];
showImgView.image =img;
showImgView.contentMode =UIViewContentModeScaleAspectFit;
[holderView
addSubview:showImgView];
[showImgView
release];
UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizeralloc]initWithTarget:selfaction:@selector(scaGesture:)];
[pinchRecognizersetDelegate:self];
[holderView
addGestureRecognizer:pinchRecognizer];
[pinchRecognizerrelease];
[self.viewaddSubview:holderView];
[holderView
release];
3.在加入這個手勢的執行方法
-(void)scaGesture:(id)sender {
[self.viewbringSubviewToFront:[(UIPinchGestureRecognizer*)senderview]];
//當手指離開螢幕時,將lastscale設定為1.0
if([(UIPinchGestureRecognizer*)senderstate]
== UIGestureRecognizerStateEnded) {
lastScale = 1.0;
return;
}
CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)senderscale]);
CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)senderview].transform;
CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
[[(UIPinchGestureRecognizer*)senderview]setTransform:newTransform];
lastScale = [(UIPinchGestureRecognizer*)senderscale];
}
4. 加入手勢的代理方法
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return ![gestureRecognizer isKindOfClass:[UIPanGestureRecognizerclass]];
}
5、運行程式,效果(注意這裡只能是以圖片中心放大的,不能進行移動圖片,若要移動圖片,需要修改其Transform部分代碼)
下面這個圖是從別處找來的,
自己並上傳比較麻煩, 呵呵
注意:請在真機上運行,在模擬器中無法類比Pinch手勢, 按住option和shift鍵在模擬器上也能類比出兩個手指的手勢