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

iOS:Quartz 2D 繪圖實作手寫板與相機取捨

編輯:iOS 開發綜合

Quartz 2D 是 iOS 上最底層的 2D 繪圖 API。本文示範兩個常見應用:用 Core Graphics 實作一個手寫/塗鴉畫板,以及呼叫相機拍照並顯示結果。

一、用 Quartz 2D 實作畫板

核心思路是:把使用者手指經過的每一個座標存成物件陣列,然後在 drawRect: 中把這些點串成路徑描邊。

先定義一個簡單的點模型:

// Dog.h
@interface Dog : NSObject
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@end

視圖的實作:

// drawTestView.m
#import "drawTestView.h"
#import "Dog.h"

@implementation drawTestView

@synthesize dogs, tempdogs;

// 懶載入:已完成的多筆線條
- (NSMutableArray *)dogs {
    if (dogs == nil) dogs = [NSMutableArray array];
    return dogs;
}

// 懶載入:目前這筆正在繪製的線條
- (NSMutableArray *)tempdogs {
    if (tempdogs == nil) tempdogs = [NSMutableArray array];
    return tempdogs;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(ctx, [[UIColor greenColor] CGColor]);

    // 把每一筆線條依序描繪出來
    [dogs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSMutableArray *arr = [dogs objectAtIndex:idx];
        for (int i = 0; i < [arr count]; i++) {
            Dog *dog = (Dog *)[arr objectAtIndex:i];
            if (i == 0) {
                CGContextMoveToPoint(ctx, dog.x, dog.y);   // 第一個點:移動畫筆
            } else {
                CGContextAddLineToPoint(ctx, dog.x, dog.y); // 其後:連線
            }
        }
    }];

    [[UIColor blackColor] setStroke];
    CGContextDrawPath(ctx, kCGPathStroke);   // 一次描邊
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];

    Dog *dog = [[Dog alloc] init];
    dog.x = location.x;
    dog.y = location.y;

    [self.tempdogs addObject:dog];
    [self.dogs addObject:self.tempdogs];   // 開始新的一筆
    [self setNeedsDisplay];                 // 觸發 drawRect:
}

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

    Dog *dog = [[Dog alloc] init];
    dog.x = location.x;
    dog.y = location.y;

    [self.tempdogs addObject:dog];
    [self.dogs addObject:[self.tempdogs copy]];   // 更新最後一筆的內容
    [self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [tempdogs removeAllObjects];   // 本筆結束,清空暫存
}

@end

繪製的關鍵三步永遠是:CGContextMoveToPoint 起筆、CGContextAddLineToPoint 連線、CGContextDrawPath 收尾。另外,任何在 touchesMoved: 中的資料變更都必須搭配 setNeedsDisplay 才會反映到畫面上。

效能提醒:這個實作每次移動都呼叫 setNeedsDisplay,會導致整條 drawRect 重跑並重繪所有歷史線條。線條一多就會明顯掉幀。實務上應改為「只繪製最新一段」的增量式做法,或改用 CAShapeLayer/UIBezierPath 讓系統替你快取。

二、相機的使用

使用 UIImagePickerController 前,控制器必須同時遵循兩個協議:

@interface MyViewController : UIViewController
    <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@end

只寫 UIImagePickerControllerDelegate 會出現警告,甚至導致代理方法不被呼叫——這是為什麼:UIImagePickerController 內部會以 UINavigationController 的形式呈現,兩個協議缺一不可。

imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;

進入相機:

- (IBAction)goImagePicker:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;  // 前置鏡頭
    } else {
        // 模擬器或無相機的裝置,退回相簿
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }

    self.imagePicker.allowsEditing = YES;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

實作兩個代理方法:

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];

    // 依原始比例調整 imageView 高度,避免圖片變形
    _imageSelect.frame = CGRectMake(_imageSelect.frame.origin.x,
                                    _imageSelect.frame.origin.y,
                                    _imageSelect.frame.size.width,
                                    _imageSelect.frame.size.width * image.size.height / image.size.width);
    _imageSelect.image = image;

    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

注意 dismiss 一定要在兩個代理方法中**都**呼叫。只處理「已選取」而忘了「已取消」,使用者按下取消後會被卡在相機畫面裡。

三、幾個實務細節

1. 隱私權宣告。使用相機與相簿都必須在 Info.plist 中說明用途:NSCameraUsageDescription、NSPhotoLibraryUsageDescription。缺少任一個會直接 crash。

2. 拍照與選片的資訊鍵不同。相機模式請取 UIImagePickerControllerOriginalImage;只有開啟 allowsEditing 時才有 UIImagePickerControllerEditedImage。若未開啟裁剪卻去取 EditedImage,會拿到 nil。

3. 前後鏡頭切換。可透過 toggleCameraButton 或自行呼叫 startCameraCapture 相關 API;切換前建議先確認 cameraDevice 是否可用。

4. UIImagePickerController 已被 PHPicker 取代。iOS 14 起建議改用 PhotosUI 的 PHPickerViewController,它**不需要**相簿權限即可選取使用者授權的特定照片,審核與使用者體驗都更好;相機拍攝則仍可沿用 UIImagePickerController 或改用 AVFoundation 自建。

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