做一個畫板,是很值得練習的題目——它同時涵蓋了手勢處理、離屏繪製、路徑管理與圖片混合。本文記錄一個完整實作的每個環節。
功能清單:畫線、改線寬、改顏色、橡皮擦、復原、清屏、選圖片並可縮放旋轉、最後存進相冊。

這個 view 可能從 XIB 載入,也可能用程式碼建立,因此兩個初始化方法都要實作:
#import <UIKit/UIKit.h> @interface DrawView : UIView /** 線寬 */ @property (nonatomic, assign) NSInteger lineWidth; /** 顏色 */ @property (nonatomic, strong) UIColor *pathColor; /** 圖片 */ @property (nonatomic, strong) UIImage *image; - (void)clear; - (void)undo; @end
- (void)awakeFromNib {
[self setUp];
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setUp];
}
return self;
}
// 自訂初始化方法
- (void)setUp {
// 拖曳手勢負責畫線
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self addGestureRecognizer:pan];
// 預設線寬
_lineWidth = 2;
}
原生的 UIBezierPath 無法設定線條顏色(顏色是在 stroke 時由 context 決定的),若要把顏色跟著每條路徑一起保存,就得自己包一層:
#import <UIKit/UIKit.h> @interface DrawPath : UIBezierPath @property (nonatomic, strong) UIColor *pathColor; @end
這一步是整個設計的核心決定:因為顏色被存進路徑物件裡,所以「復原」只要把物件從陣列移除即可,不需要重畫整個畫布。
@interface DrawView ()
@property (nonatomic, strong) DrawPath *path;
/** 保存所有路徑的陣列 */
@property (nonatomic, strong) NSMutableArray *pathArr;
@end
// 懶載入
- (NSMutableArray *)pathArr {
if (_pathArr == nil) {
_pathArr = [NSMutableArray array];
}
return _pathArr;
}
- (void)pan:(UIPanGestureRecognizer *)pan {
// 取得目前觸摸點
CGPoint startP = [pan locationInView:self];
if (pan.state == UIGestureRecognizerStateBegan) {
// 手指按下,建立一條新路徑
_path = [[DrawPath alloc] init];
_path.lineWidth = _lineWidth;
_path.pathColor = _pathColor;
// 注意:必須在這裡就加入陣列
// 若等到手指抬起才加,drawRect 遍歷時找不到這條路徑,畫不出來
[_pathArr addObject:_path];
[_path moveToPoint:startP];
}
// 手指移動,持續延長線條
[_path addLineToPoint:startP];
// 觸發重繪
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
// 把陣列裡所有內容依序畫出來
for (id item in self.pathArr) {
if ([item isKindOfClass:[UIImage class]]) {
// 是圖片,直接畫進目前區域
UIImage *image = (UIImage *)item;
[image drawInRect:rect];
} else {
// 是路徑,用自身帶的顏色描邊
DrawPath *path = (DrawPath *)item;
[path.pathColor set];
[path stroke];
}
}
}
這裡有個巧思:路徑陣列裡同時放 DrawPath 與 UIImage,drawRect 依型別分別處理。這樣「圖片」和「筆跡」在資料層是平等的一等公民,復原、清屏等操作都能一視同仁。
- (void)setImage:(UIImage *)image {
_image = image;
[self.pathArr addObject:image];
// 必須重繪才會顯示
[self setNeedsDisplay];
}
把直接操作陣列的行為封裝在 DrawView 內部,呼叫端不必知道實作細節:
- (void)clear {
[self.pathArr removeAllObjects];
[self setNeedsDisplay];
}
- (void)undo {
[self.pathArr removeLastObject];
[self setNeedsDisplay];
}
@interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> @property (weak, nonatomic) IBOutlet DrawView *drawView; @end
- (IBAction)clear:(id)sender {
[_drawView clear];
}
- (IBAction)undo:(id)sender {
[_drawView undo];
}
- (IBAction)eraser:(id)sender {
// 橡皮擦的實作很樸素:把筆跡顏色設成背景色
// 缺點是無法擦除「底下的圖片」,只能蓋住同層筆跡
_drawView.pathColor = _drawView.backgroundColor;
_drawView.lineWidth = 20;
}
- (IBAction)changeLineWidth:(UISlider *)sender {
_drawView.lineWidth = sender.value;
}
- (IBAction)changeColor:(UIButton *)sender {
_drawView.pathColor = sender.backgroundColor;
}
- (IBAction)pickPhoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
picker.delegate = self;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info {
UIImage *image = info[UIImagePickerControllerOriginalImage];
// 建立專門處理圖片的 view
ImageHandleView *handleView = [[ImageHandleView alloc] initWithFrame:self.drawView.bounds];
handleView.handleCompletionBlock = ^(UIImage *image) {
_drawView.image = image;
};
[self.drawView addSubview:handleView];
handleView.image = image;
[self dismissViewControllerAnimated:YES completion:nil];
}
關於橡皮擦:用背景色覆蓋是一個常見的取巧做法,實作成本極低,但有明顯限制——它只能蓋住同層的筆跡,無法擦掉底下的圖片,而且若背景不是純色就會露餡。若要真正的擦除,需要改用 Core Graphics 的 CGContextSetBlendMode 搭配 destination-out 混合模式,或改用 CAShapeLayer 遮罩。這是一個值得留意的設計取捨。
- (IBAction)save:(id)sender {
[UIView animateWithDuration:0.15 animations:^{
// 開啟位圖上下文
UIGraphicsBeginImageContextWithOptions(_drawView.bounds.size, NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 把畫板的圖層渲染進上下文
[_drawView.layer renderInContext:ctx];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 存入相冊
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
// 保存期間淡出,給使用者回饋
self.drawView.alpha = 0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.15 animations:^{
self.drawView.alpha = 1;
}];
}];
}
// 這個方法簽名必須完全一致,否則不會被呼叫
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
NSLog(@"保存成功");
}
從相冊選完圖片,若要讓使用者調整位置與大小,問題就來了:UIImage 不能做這些變形操作,能做的是 UIImageView。解法是包一個專門的 view,內部放 UIImageView,手勢都加在 imageView 上。
#import <UIKit/UIKit.h> @interface ImageHandleView : UIView /** 圖片 */ @property (nonatomic, strong) UIImage *image; /** 處理完成後的回呼 */ @property (nonatomic, strong) void (^handleCompletionBlock)(UIImage *image); @end
#import "ImageHandleView.h"
@interface ImageHandleView () <UIGestureRecognizerDelegate>
@property (nonatomic, weak) UIImageView *imageView;
@end
@implementation ImageHandleView
// 攔截 hitTest,讓觸摸事件不要穿透到下面的畫板
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
return _imageView;
}
- (UIImageView *)imageView {
if (_imageView == nil) {
UIImageView *imageV = [[UIImageView alloc] initWithFrame:self.bounds];
_imageView = imageV;
// 必須允許互動,手勢才會生效
_imageView.userInteractionEnabled = YES;
[self setUpGestureRecognizer];
[self addSubview:imageV];
}
return _imageView;
}
#pragma mark - 加入手勢
- (void)setUpGestureRecognizer {
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[_imageView addGestureRecognizer:pan];
UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotation:)];
rotation.delegate = self;
[_imageView addGestureRecognizer:rotation];
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
pinch.delegate = self;
[_imageView addGestureRecognizer:pinch];
// 長按代表「確認」,把目前狀態燒進畫板
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[_imageView addGestureRecognizer:longPress];
}
#pragma mark - 平移
- (void)pan:(UIPanGestureRecognizer *)pan {
CGPoint tranp = [pan translationInView:self.imageView];
self.imageView.transform = CGAffineTransformTranslate(self.imageView.transform, tranp.x, tranp.y);
[pan setTranslation:CGPointZero inView:self.imageView];
}
#pragma mark - 旋轉
- (void)rotation:(UIRotationGestureRecognizer *)rotation {
self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, rotation.rotation);
rotation.rotation = 0; // 相對值必須歸零
}
#pragma mark - 縮放
- (void)pinch:(UIPinchGestureRecognizer *)pinch {
self.imageView.transform = CGAffineTransformScale(self.imageView.transform, pinch.scale, pinch.scale);
pinch.scale = 1; // 相對值必須歸零
}
#pragma mark - 長按確認
- (void)longPress:(UILongPressGestureRecognizer *)longPress {
if (longPress.state == UIGestureRecognizerStateBegan) {
// 用淡出淡入製造「閃一下」的回饋
[UIView animateWithDuration:0.25 animations:^{
self.imageView.alpha = 0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.25 animations:^{
self.imageView.alpha = 1;
} completion:^(BOOL finished2) {
// 把目前這個 view 的呈現結果渲染成一張新圖
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self.layer renderInContext:ctx];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 透過 block 把結果交出去
if (_handleCompletionBlock) {
_handleCompletionBlock(image);
}
[self removeFromSuperview];
}];
}];
}
}
#pragma mark - 允许多手勢並存
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
- (void)setImage:(UIImage *)image {
_image = image;
self.imageView.image = image;
}
@end
ImageHandleView 處理完圖片後,需要把結果交回 DrawView。最直白的做法是在 ImageHandleView 裡 import DrawView 並直接操作它——但這樣兩個類別就綁死了。
這裡用 Block 解耦:ImageHandleView 只負責把結果透過 handleCompletionBlock 丟出去,完全不知道接收者是誰。由控制器負責把兩者接起來:
handleView.handleCompletionBlock = ^(UIImage *image) {
_drawView.image = image;
};
用 delegate 也能達到同樣效果。重點是依賴方向要保持單向:ImageHandleView 不該知道 DrawView 的存在。
