本篇分享一個經典的互動效果:讓圖片跟隨雙指捏合的距離來放大或縮小。這個功能透過 touchesMoved:withEvent: 方法實作,每當手指在螢幕上移動時,該方法都會被呼叫。
1. 偵測手指的數量:
NSArray * touchesArr=[[event allTouches] allObjects];
NSLog(@"手指個數%d",[touchesArr count]);
2. 取得兩指座標,藉此計算兩指之間的距離:
p1=[[touchesArr objectAtIndex:0] locationInView:self.view];
p2=[[touchesArr objectAtIndex:1] locationInView:self.view];
3. 當距離增加時放大圖片,距離減小時縮小圖片,透過調整 imageView 的 frame 來控制大小:
imageView.frame=CGRectMake(imgFrame.origin.x-addwidth/2.0f, imgFrame.origin.y-addheight/2.0f, imgFrame.size.width, imgFrame.size.height);
這裡的關鍵在於以兩指間的距離變化量(addwidth、addheight)去推算縮放比例,並以原點微調讓圖片以中心為基準平滑縮放。如此一來,使用者便能透過雙指捏合,直觀地縮放圖片了。