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

iOS 放大鏡效果:自訂 View 實作 Touch 放大

編輯:iOS 開發綜合

放大鏡效果常用於看圖、閱讀小字或檢查畫面細節。在 iOS 中,可以自訂一個 UIView,根據觸摸位置擷取畫面內容並放大顯示。

建立放大鏡視圖

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

@interface ViewController : UIViewController

@property (nonatomic, strong) MagnifierV *magnifier;

@end

加入畫面與放大鏡

- (void)viewDidLoad {
    [super viewDidLoad];

    UIImageView *imageView =
        [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"changmen.jpg"]];

    imageView.frame = CGRectMake(0, 0, 320, 548);
    [self.view addSubview:imageView];

    self.magnifier =
        [[MagnifierV alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];

    self.magnifier.viewToMagnify = self.view;
    [self.view addSubview:self.magnifier];

    self.magnifier.hidden = YES;
}

處理觸摸事件

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.magnifier.hidden = NO;

    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];

    self.magnifier.touchPoint = point;
    [self.magnifier setNeedsDisplay];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];

    self.magnifier.touchPoint = point;
    [self.magnifier setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    self.magnifier.hidden = YES;
}

這個範例的重點是:MagnifierV 會依 touchPoint 取得對應區域,再將該區域放大繪製。使用時要把放大鏡視圖放在最上層,並在觸摸開始、移動與結束時更新位置與可見狀態。

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