本文分享一個支持三種顏色畫筆與橡皮擦的畫板 Demo,在 iPhone 6.1 系統上測試通過。
項目中 PaintView.m 承擔畫板的繪製職責,把它與三個顏色按鈕一同添加到 ViewController 的 view 上,即構成程序主界面。
畫板並不是「邊畫邊往上下文上描」,而是把每一筆記錄成數據:每一筆包含一個顏色與一串坐標點,全部存進 linesArray。重繪時遍歷這個數組,逐筆回放。這樣做的好處是天然支持重畫、清空與後續擴展成「支持撤銷」。
橡皮擦的處理比較取巧:並非真正擦除像素,而是把靠近觸摸點的筆畫位置記到該筆的 eraseArray 中,重繪時用白色覆蓋這些點,視覺上達到擦拭效果。
#import "PaintView.h"
#import <QuartzCore/QuartzCore.h>
@implementation PaintView
@synthesize paintColor = _paintColor;
@synthesize erase;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowOpacity = 0.8;
self.layer.shadowOffset = CGSizeMake(5, 5);
self.backgroundColor = [UIColor whiteColor];
self.paintColor = [UIColor blackColor];
linesArray = [[NSMutableArray alloc] init];
UIPanGestureRecognizer *panGesture =
[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
[self addGestureRecognizer:panGesture];
[panGesture release];
}
return self;
}
- (void)dealloc
{
[linesArray release];
[_paintColor release];
[super dealloc];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 20);
for (NSDictionary *lineDic in linesArray) {
UIColor *lineColor = [lineDic objectForKey:@"color"];
CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
CGMutablePathRef paintPath = CGPathCreateMutable();
NSArray *linePointArray = [lineDic objectForKey:@"line"];
for (NSInteger i = 0; i < linePointArray.count; i++) {
CGPoint point = [[linePointArray objectAtIndex:i] CGPointValue];
if (i == 0) {
CGPathMoveToPoint(paintPath, NULL, point.x, point.y);
} else {
CGPathAddLineToPoint(paintPath, NULL, point.x, point.y);
}
}
CGContextAddPath(context, paintPath);
CGContextStrokePath(context);
// 有擦除記錄時,用白色重描一遍擦除軌跡
if ([lineDic objectForKey:@"eraseArray"]) {
NSMutableArray *eraseArray = [lineDic objectForKey:@"eraseArray"];
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGMutablePathRef erasePath = CGPathCreateMutable();
for (NSInteger i = 0; i < eraseArray.count; i++) {
CGPoint point = [[eraseArray objectAtIndex:i] CGPointValue];
if (i == 0) {
CGPathMoveToPoint(erasePath, NULL, point.x, point.y);
} else {
CGPathAddLineToPoint(erasePath, NULL, point.x, point.y);
}
}
CGContextAddPath(context, erasePath);
CGContextStrokePath(context);
}
}
}
- (void)panGesture:(UIPanGestureRecognizer *)thePan
{
CGPoint touchPoint = [thePan locationInView:self];
if (self.erase) {
if (thePan.state == UIGestureRecognizerStateChanged) {
for (NSMutableDictionary *lineDic in linesArray) {
NSMutableArray *linePointArray = [lineDic objectForKey:@"line"];
for (NSInteger i = 0; i < linePointArray.count; i++) {
CGPoint point = [[linePointArray objectAtIndex:i] CGPointValue];
CGFloat dx = point.x - touchPoint.x;
CGFloat dy = point.y - touchPoint.y;
CGFloat distance = sqrtf(dx * dx + dy * dy);
if (distance < 20) {
NSMutableArray *eraseArray;
if ([lineDic objectForKey:@"eraseArray"]) {
eraseArray = [lineDic objectForKey:@"eraseArray"];
} else {
eraseArray = [NSMutableArray array];
}
[eraseArray addObject:[NSValue valueWithCGPoint:touchPoint]];
[lineDic setObject:eraseArray forKey:@"eraseArray"];
CGRect paintRect = CGRectMake(touchPoint.x - 50, touchPoint.y - 50, 100, 100);
[self setNeedsDisplayInRect:paintRect];
continue;
}
}
}
}
} else {
if (thePan.state == UIGestureRecognizerStateBegan) {
NSMutableArray *currentLineArray =
[NSMutableArray arrayWithObject:[NSValue valueWithCGPoint:touchPoint]];
NSMutableDictionary *lineDic =
[NSMutableDictionary dictionaryWithObjectsAndKeys:currentLineArray, @"line",
_paintColor, @"color", nil];
[linesArray addObject:lineDic];
} else if (thePan.state == UIGestureRecognizerStateChanged) {
NSMutableDictionary *lineDic = [linesArray lastObject];
NSMutableArray *currentLineArray = [lineDic objectForKey:@"line"];
[currentLineArray addObject:[NSValue valueWithCGPoint:touchPoint)];
CGRect paintRect = CGRectMake(touchPoint.x - 50, touchPoint.y - 50, 100, 100);
[self setNeedsDisplayInRect:paintRect];
}
}
}
@end
局部重繪。示例用 setNeedsDisplayInRect: 只刷新觸摸點周圍 100×100 的區域,比整屏 setNeedsDisplay 高效得多,這在低端設備上差異明顯。
距離計算。示例原寫法把 powf 的兩個參數誤當成底數與指數,正確做法是用歐氏距離 sqrtf(dx*dx + dy*dy)(本文已修正),或直接比較平方值省去開方運算。
橡皮擦的局限。用白色覆蓋只在白底上成立,一旦畫板背景換色或需要疊在其他內容上,就會露出破綻。真正健壯的方案是啟用 kCGBlendModeClear 的 CGContextClearRect,配合圖層合成,才能做到真正的透明擦除。
性能與內存。linesArray 只增不減,長時間作畫會持續吃內存。可考慮在筆畫數量或總長度超閾值時,把已有內容渲染到位圖並重置數組。此外 CGMutablePathRef 用完需 CGPathRelease,ARC 不會幫你管理 Core Graphics 對象。