放大鏡是看圖、看文件時常見的輔助互動:長按後在指定位置浮現一個圓形放大視窗,拖曳時視窗內容即時跟著更新。以下是一個可直接運用的實作範例。
把 MagnifierView 類別匯入專案即可(範例專案中已附帶)。
#import <UIKit/UIKit.h> #import "MagnifierView.h" @interface ViewController : UIViewController @property (strong, nonatomic) MagnifierView *loop; @property (strong, nonatomic) NSTimer *touchTimer; @end
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"changmen.jpg"]];
image.frame = CGRectMake(0, 0, 320, 548);
[self.view addSubview:image];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 長按 0.5 秒後才顯示放大鏡,避免一般點擊也跳出來
self.touchTimer = [NSTimer scheduledTimerWithTimeInterval:0.5f
target:self
selector:@selector(addLoop)
userInfo:nil
repeats:NO];
if (self.loop == nil) {
self.loop = [[MagnifierView alloc] init];
self.loop.viewToMagnify = self.view;
}
UITouch *touch = [touches anyObject];
self.loop.touchPoint = [touch locationInView:self.view];
[self.loop setNeedsDisplay];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self handleAction:touches];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self.touchTimer invalidate];
self.touchTimer = nil;
self.loop = nil;
}
- (void)handleAction:(id)timerObj {
NSSet *touches = timerObj;
UITouch *touch = [touches anyObject];
self.loop.touchPoint = [touch locationInView:self.view];
[self.loop setNeedsDisplay];
}
- (void)addLoop {
// 注意:必須把放大鏡加到「被放大檢視之外」的父層
// 如果加進被放大的 view 本身,它會把自己也一起放大,造成遞迴
[self.loop makeKeyAndVisible];
}
viewToMagnify 指定要放大的檢視。放大鏡內部通常是呼叫該 view 的 drawRect:inContext: 或 renderInContext: 重新繪製,並以 CGAffineTransform 做放大與位移。touchesMoved: 中提早喚起(可再補判斷移動距離),才接近系統原生的手感。touchesEnded 中若未取消 timer,可能在使用者已放開手指後才觸發,導致放大鏡殘留。如果要更貼近 iOS 原生的效果,還可以加上圓形遮罩、邊框陰影,以及靠近螢幕邊緣時的視窗位置自動翻轉,避免放大鏡被畫面邊界裁掉。