有时候用CAShapeLayer或者其他矢量图形图层替代Core Graphics并不是那么切实可行。比如我们的绘图应用:我们用线条完美地完成了矢量绘制。但是设想一下如果我们能进一步提高应用的性能,让它就像一个黑板一样工作,然后用『粉笔』来绘制线条。模拟粉笔最简单的方法就是用一个『线刷』图片然后将它粘贴到用户手指碰触的地方,但是这个方法用CAShapeLayer没办法实现。
我们可以给每个『线刷』创建一个独立的图层,但是实现起来有很大的问题。屏幕上允许同时出现图层上线数量大约是几百,那样我们很快就会超出的。这种情况下我们没什么办法,就用Core Graphics吧(除非你想用OpenGL做一些更复杂的事情)。
我们的『黑板』应用的最初实现见清单13.3,我们更改了之前版本的DrawingView,用一个画刷位置的数组代替UIBezierPath。图13.2是运行结果
清单13.3 简单的类似黑板的应用
1 #import "DrawingView.h" 2 #import 3 #define BRUSH_SIZE 32 4 5 @interface DrawingView () 6 7 @property (nonatomic, strong) NSMutableArray *strokes; 8 9 @end 10 11 @implementation DrawingView 12 13 - (void)awakeFromNib 14 { 15 //create array 16 self.strokes = [NSMutableArray array]; 17 } 18 19 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 20 { 21 //get the starting point 22 CGPoint point = [[touches anyObject] locationInView:self]; 23 24 //add brush stroke 25 [self addBrushStrokeAtPoint:point]; 26 } 27 28 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 29 { 30 //get the touch point 31 CGPoint point = [[touches anyObject] locationInView:self]; 32 33 //add brush stroke 34 [self addBrushStrokeAtPoint:point]; 35 } 36 37 - (void)addBrushStrokeAtPoint:(CGPoint)point 38 { 39 //add brush stroke to array 40 [self.strokes addObject:[NSValue valueWithCGPoint:point]]; 41 42 //needs redraw 43 [self setNeedsDisplay]; 44 } 45 46 - (void)drawRect:(CGRect)rect 47 { 48 //redraw strokes 49 for (NSValue *value in self.strokes) { 50 //get point 51 CGPoint point = [value CGPointValue]; 52 53 //get brush rect 54 CGRect brushRect = CGRectMake(point.x - BRUSH_SIZE/2, point.y - BRUSH_SIZE/2, BRUSH_SIZE, BRUSH_SIZE); 55 56 //draw brush stroke  57 [[UIImage imageNamed:@"Chalk.png"] drawInRect:brushRect]; 58 } 59 } 60 @end