在touchEnded里面将这次touch操作所经过的点存到一个可变长数组里面, 然后把这个数组存到一个dictionary里面. 在drawset每次画之前先遍历这个dictionary里面的数组(每组点), 把这些点画出来, 然后再画当前touch操作.
代码如下:
//类定义如下 @interface KeepDraw: UIView{ NSMutableArray * currentPoints; NSMutableDictionary * savedPoints; int dictPos;//dictPos用来给savedPoints设定key. 其实也可以用savedPoints.count来设定, 但是比较ambiguous. }
方法如下:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ NSMutableArray * tmp = [[NSMutableArray alloc] init]; for(int i = 0; i < currentPoints.count - 1; i ++)//把每一组值都存到一个临时数组里面, 然后再交给savedPoints [tmp addObjet: [currentPoints objectAtIndex: i]]; [savedPoint setObject: tmp forKey: [NSString stringWithFormat: @"%d", dictPos]]; dictPos ++; [currentPoints removeAllObjects];//记得要removecurrentPoints, 要不然每次存到savedPoints里面的东西都会重复之前存的. } - (void)touchesCancelled:(NSSet *)touches withEven: (UIEvent*) event{ [self touchesEnded: touches withEvent: event]; } - (void) drawRect: (CGRect)rect{ if(currentPoints.count == 0) return; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 4); CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]); for(int i = 0; i < dictPos; i ++){ //就是这里了, 从savedPoints里面把每一组值都取出来, 然后画出来. NSArray * tmp = [savedPoints objectForKey: [NSString stringWithFormat: @"%d", i]]; for(int j = 0; j < tmp.count - 1; j ++) drawGraphics(j); } for(int i = 0; i < currentPoints.count - 1; i ++) drawGraphics(i); }
drawGraphics 的定义如下:
void drawGraphics(int i){ CGPoint x1 = [[tmp objectAtIndex: j] CGPointValue]; CGPoint x2 = [[tmp objectAtIndex: j + 1] CGPointValue]; CGContextMoveToPoint(context, x1.x, x1.y); CGContextAddLineToPoint(context, x2.x, x2.y); CGContextStrokPath(context); }