在视图控制器类中添加视图
-(void)loadView//一次
{
self.view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)] autorelease];
kView *KView = [[kView alloc]initWithFrame:self.view.frame];
KView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:KView];
[KView release];
}
然后在UIView的点击和移动时间里面获取点划线
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"开始点击");
//在数组里面存数组,大数组装线,小数组装点
NSMutableArray *pointsArray = [NSMutableArray array];
//
[_lineArray addObject:pointsArray];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"移动");
// 通过touches获取点
UITouch *touch = [touches anyObject];
CGPoint pointe = [touch locationInView:self];// 获取当前点的坐标
NSValue *value = [NSValue valueWithCGPoint:pointe];// 将坐标转化成NSValue类型
NSMutableArray *pointArray = [_lineArray lastObject];// 取出linesArray里面的最后一个数组
[pointArray addObject:value];// 将value加入到内层数组里面
[self setNeedsDisplay];
}
在drawRect方法(画图方法)里面实现画图
- (void)drawRect:(CGRect)rect
{
// Drawing code
NSLog(@"哈哈哈,我启动了!!");
// C语言的方法调用
CGContextRef context = UIGraphicsGetCurrentContext();// 获得绘图上下文
CGContextSetStrokeColorWithColor(context,[UIColor blackColor].CGColor);//设置画笔颜色
CGContextSetLineWidth(context, 2.0f); // 设置画笔的粗细
// 判断数组是否为空(只点击,不移动)
if (_lineArray.count == 0)
{
return;
}
for (int i = 0; i<[_lineArray count]; i++)
{
NSMutableArray *arr = [_lineArray objectAtIndex:i];
//判断数组里面的数组是否为空
if (arr.count == 0)
{
continue;
}// 只有一个点的情况
else if(arr.count == 1)
{
NSValue *value1 = [arr objectAtIndex:0];
CGPoint point1 = [value1 CGPointValue];
CGContextMoveToPoint(context, point1.x, point1.y);
CGContextAddLineToPoint(context, point1.x+0.01, point1.y+0.01);
}
else
{
for (int j = 0; j<[arr count]-1; j++)
{
// 获取数组里数组的元素
NSValue *value1 = [arr objectAtIndex:j];
NSValue *value2 = [arr objectAtIndex:j+1];
// 数组里数组的元素转换成point类型
CGPoint point1 = [value1 CGPointValue];
CGPoint point2 = [value2 CGPointValue];
// 添加点
CGContextMoveToPoint(context, point1.x, point1.y);
CGContextAddLineToPoint(context, point2.x, point2.y);
}
}
}
CGContextStrokePath(context);
}