本文示範如何利用雙指(Pinch)手勢縮放圖片:當兩根手指往不同方向拖動時,圖片會隨之放大或縮小,核心概念是等比縮放。
先在初始化時記錄參數:
- (void)viewDidLoad
{
[super viewDidLoad];
lastDistance = 0.0;
imageStartHeight = self.scaleImage.frame.size.height;
imageStartWidth = self.scaleImage.frame.size.width;
}
接著在 touchesMoved 中處理縮放邏輯:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint point1;
CGPoint point2;
CGFloat sub_x;
CGFloat sub_y;
CGFloat currentDistance;
CGRect imageFrame;
NSArray *touchArray = [[event allTouches] allObjects];
if ([touchArray count] >= 2) {
point1 = [[touchArray objectAtIndex:0] locationInView:self.view];
point2 = [[touchArray objectAtIndex:1] locationInView:self.view];
sub_x = point1.x - point2.x;
sub_y = point1.y - point2.y;
currentDistance = sqrtf(sub_x * sub_x + sub_y * sub_y);
if (lastDistance > 0) {
imageFrame = self.scaleImage.frame;
if (currentDistance > lastDistance + 2) {
imageFrame.size.width += 10;
if (imageFrame.size.width > 1000) imageFrame.size.width = 1000;
lastDistance = currentDistance;
}
if (currentDistance < lastDistance - 2) {
imageFrame.size.width -= 10;
if (imageFrame.size.width < 50) imageFrame.size.width = 50;
lastDistance = currentDistance;
}
if (currentDistance == lastDistance) {
imageFrame.size.height = imageStartHeight * imageFrame.size.width / imageStartWidth;
float addwidth = imageFrame.size.width - self.scaleImage.frame.size.width;
float addheight = imageFrame.size.height - self.scaleImage.frame.size.height;
self.scaleImage.frame = CGRectMake(imageFrame.origin.x - addwidth/2.0f, imageFrame.origin.y - addheight/2.0f, imageFrame.size.width, imageFrame.size.height);
}
} else {
lastDistance = currentDistance;
}
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
lastDistance = 0;
}
關鍵在於:判斷兩指間的距離變化,當差距超過一定門檻時,就對圖片的 frame 進行等比縮放,藉此達到縮放目的。歡迎有其他做法的朋友一起討論。