NSMutableArray *allPoint;
NSMutableArray *allLine;
allLine 在view init 的时候初始化
接下来要捕获手指和设备的交互的位置。
代码如下:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
allPoint = [[NSMutableArrayalloc] init];
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self];
LocationMode *mode = [[LocationModealloc] init];
mode.x = location.x;
mode.y = location.y;
[allPoint addObject:mode];
[mode release];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self];
LocationMode *mode = [[LocationModealloc] init];
mode.x = location.x;
mode.y = location.y;
[allPoint addObject:mode];
[mode release];
[selfsetNeedsDisplay];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[allLine addObject:allPoint];
[allPoint release];
[selfsetNeedsDisplay];
}
现在要做的就是 去将这些点绘制出来
- (void)drawRect:(CGRect)rect
因为我们每次在触摸屏幕的时候,在touchend 的时候才会将 点数组 添加到 allLine 数组中,所以要分两次绘制,就是之前的所有路径,当前正在绘制的路径。
具体代码:
CGContextRef cgContext = UIGraphicsGetCurrentContext();
//设置笔冒
CGContextSetLineCap(cgContext,kCGLineCapRound);
//设置画线的连接处 拐点圆滑
CGContextSetLineJoin(cgContext,kCGLineJoinRound);
CGContextBeginPath(cgContext);
if(allLine && allLine.count > 0)
{
for(int j =0;j<allLine.count;j++)
{
NSMutableArray *array = [allLineobjectAtIndex:j];
if(array)
{
[array retain];
for(int i =0;i<array.count;i++)
{
LocationMode *location = [arrayobjectAtIndex:i];
if (i == 0)
{
CGContextMoveToPoint(cgContext, location.x, location.y);
}
else
{
CGContextAddLineToPoint(cgContext, location.x, location.y);
}
}
[array release];
}
}
}
if(allPoint &&allPoint.count >0)
{
for(int i =0;i<allPoint.count;i++)
{
LocationMode *location = [allPointobjectAtIndex:i];
if (i == 0)
{
CGContextMoveToPoint(cgContext, location.x, location.y);
}
else
{
CGContextAddLineToPoint(cgContext, location.x, location.y);
}
}
}
CGContextSetFillColorWithColor(cgContext, [[UIColorblueColor] CGColor]);
CGContextSetStrokeColorWithColor(cgContext, [UIColorredColor].CGColor);
CGContextSetLineWidth(cgContext,3.0);
CGContextStrokePath(cgContext);