想讓使用者用兩根手指就能放大照片、轉動照片?在 iOS 裡最直接的作法,就是替檢視掛上手勢辨識器(Gesture Recognizer)。本篇動手做一個小範例:把一張圖片放進 UIImageView,然後加上 UIPinchGestureRecognizer(捏合)與 UIRotationGestureRecognizer(旋轉),讓圖片可以自由縮放與旋轉。
UIImageView 預設並不接收觸碰事件,所以第一步一定要把 userInteractionEnabled 設為 YES,否則手勢加得再漂亮也不會有任何反應。這是新手最常踩的第一個坑。
建立手勢時要傳入兩個參數:事件擁有者(target)與回呼方法(action)。接著用 addGestureRecognizer: 把手勢掛到需要響應的檢視上,並把 delegate 設為自己。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UIGestureRecognizerDelegate>
{
// 捏合手勢:負責放大、縮小
UIPinchGestureRecognizer *_pinchGes;
// 旋轉手勢:負責旋轉圖片
UIRotationGestureRecognizer *_rotGes;
}
@end
預設情況下,系統一次只會讓一個手勢生效。也就是說,當你捏合的同時想轉動圖片,其中一個手勢會被判定失敗。要打破這個限制,就實作 gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: 並回傳 YES。
// 回傳 YES:允許同時響應多個手勢
// 回傳 NO:一次只響應一個手勢
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
旋轉手勢的 rotation 代表的是「這一次移動所產生的弧度差」,而不是絕對角度。因此正確作法是把這個差值疊加進既有的 transform,然後立刻把 rotation 歸零,讓下一次回呼重新從 0 開始計算。
- (void)rotAct:(UIRotationGestureRecognizer *)rot {
UIImageView *iView = (UIImageView *)rot.view;
// 把本次旋轉量疊加進現有的變換矩陣
iView.transform = CGAffineTransformRotate(iView.transform, rot.rotation);
// 角度歸零,準備接收下一次位移
rot.rotation = 0;
}
捏合手勢的 scale 也是相對值,同樣需要疊加後歸位:
- (void)pinchAct:(UIPinchGestureRecognizer *)pinch {
UIImageView *iView = (UIImageView *)pinch.view;
// 以縮放方式產生新矩陣:原矩陣、x 比例、y 比例
iView.transform = CGAffineTransformScale(iView.transform, pinch.scale, pinch.scale);
// 縮放值歸位為 1
pinch.scale = 1;
}
- (void)viewDidLoad {
[super viewDidLoad];
UIImage *image = [UIImage imageNamed:@"17_3.png"];
UIImageView *iView = [[UIImageView alloc] initWithImage:image];
iView.frame = CGRectMake(50, 80, 200, 300);
// 關鍵:讓圖片檢視可以接收互動事件
iView.userInteractionEnabled = YES;
[self.view addSubview:iView];
// 建立捏合手勢
_pinchGes = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAct:)];
[iView addGestureRecognizer:_pinchGes];
// 建立旋轉手勢
_rotGes = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotAct:)];
[iView addGestureRecognizer:_rotGes];
// 設定代理,才能同時響應
_pinchGes.delegate = self;
_rotGes.delegate = self;
}
整篇的關鍵其實只有三件事:第一,UIImageView 要開 userInteractionEnabled;第二,delegate 要設好並實作同時辨識的代理方法;第三,pinch 的 scale 與 rotation 的 rotation 都是「增量」,用完記得歸位。把這三點掌握好,任何可縮放、可旋轉的檢視都能如法炮製。