您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 放大鏡效果實作範例

編輯:iOS 開發綜合

放大鏡是看圖、看文件時常見的輔助互動:長按後在指定位置浮現一個圓形放大視窗,拖曳時視窗內容即時跟著更新。以下是一個可直接運用的實作範例。

使用方式

把 MagnifierView 類別匯入專案即可(範例專案中已附帶)。

ViewController.h

#import <UIKit/UIKit.h>
#import "MagnifierView.h"

@interface ViewController : UIViewController

@property (strong, nonatomic) MagnifierView *loop;
@property (strong, nonatomic) NSTimer *touchTimer;

@end

ViewController.m

- (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 做放大與位移。
  • 避免自我遞迴:放大鏡檢視一定要加在「不是被放大對象」的父層上,否則會出現無限遞迴的怪異畫面。程式註解裡也特別標了這一點。
  • 為何用 timer 做長按判定:直接顯示放大鏡會讓每次點擊都跳出一個視窗,體驗很差。加上 0.5 秒的延遲並在 touchesMoved: 中提早喚起(可再補判斷移動距離),才接近系統原生的手感。
  • 記得 invalidate:touchesEnded 中若未取消 timer,可能在使用者已放開手指後才觸發,導致放大鏡殘留。

如果要更貼近 iOS 原生的效果,還可以加上圓形遮罩、邊框陰影,以及靠近螢幕邊緣時的視窗位置自動翻轉,避免放大鏡被畫面邊界裁掉。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved