1. 绘制一条直线
1.1 声明全局属性,用来存放触摸屏幕时的初始坐标点和路径
@property (nonatomic,assign) CGPoint locPoint;
@property (nonatomic,strong) UIBezierPath *path;
1.2 在触摸屏幕事件里
*获取触摸对象
*获取最初触摸屏幕时的点
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
UITouch *touch = touches.anyObject;
CGPoint locPoint = [touch locationInView:touch.view];
self.locPoint = locPoint;
}
1.3 在触摸屏幕移动的事件中
*获取触摸对象
*创建路径
*获取在屏幕移动时的坐标点
*重绘
说明:因为在移动事件中创建路径,所以一旦手指离开屏幕重新触摸移动就会重新绘制一条新的直线
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event{
UITouch *touch = touches.anyObject;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:self.locPoint];
CGPoint currentPoint = [touch locationInView:touch.view];
[path addLineToPoint:currentPoint];
self.path = path;
[self setNeedsDisplay];
}
1.4 绘制图形
- (void)drawRect:(CGRect)rect {
[self.path stroke];
}
效果:
当点击屏幕不松手后,移动位置,绘制出一条从最初触摸屏幕时的点到最后停止时的点的一条直线
2 绘制多条直线
2.1 代码部分基本一致,只是路径的创建位置不同,touchesBegan:
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
UITouch *touch = touches.anyObject;
CGPoint locPoint = [touch locationInView:touch.view];
self.locPoint = locPoint;
}
2.2 touchesMoved:
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event{
[self.path moveToPoint:self.locPoint];
UITouch *touch = touches.anyObject;
CGPoint currentPoint = [touch locationInView:touch.view];
[self.path addLineToPoint:currentPoint];
[self setNeedsDisplay];
}
2.3 路径的创建使用了一个懒加载的方式:
- (UIBezierPath *)path{
if (!_path) {
_path = [UIBezierPath bezierPath];
}
return _path;
}
实现效果图:
3.绘制触摸路径 代码和前两种几乎一致,同样只是路径的创建位置不同,实现的效果不同而已
3.1 touchesBegan:
不同点在于在这里创建路径后,赋值给全局路径属性,这样每一次移动都在原来的路径上追加了一条线,执行重绘时,就会按照触摸屏幕的轨迹绘制线了
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
UITouch *touch = touches.anyObject;
CGPoint locPoint = [touch locationInView:touch.view];
UIBezierPath *path = [[UIBezierPath alloc]init];
[path moveToPoint:locPoint];
self.path = path;
}
3.2 touchesMoved:
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event{
UITouch *touch = touches.anyObject;
CGPoint currentPoint = [touch locationInView:touch.view];
[self.path addLineToPoint:currentPoint];
[self setNeedsDisplay];
}
3.3 效果图: