绘图-三种线样式

  1. 绘制一条直线

1.1 声明全局属性,用来存放触摸屏幕时的初始坐标点和路径

@property (nonatomic,assign) CGPoint locPoint; 
@property (nonatomic,strong) UIBezierPath *path;
1.2 在触摸屏幕事件里
    @ 获取触摸对象
    @ 获取最初触摸屏幕时的点
1.3 在触摸屏幕移动的事件中
    @ 获取触摸对象
    @ 创建路径
    @ 获取在屏幕移动时的坐标点
    @ 重绘
1.4 绘制图形

说明: 因为在移动事件中创建路径,所以一旦手指离开屏幕重新触摸移动就会重新绘制一条新的直线

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    //创建触摸对象
    UITouch *touch = touches.anyObject;
    
    //获取最初的点
    CGPoint locPoint = [touch locationInView:touch.view];
    
    //赋值
    self.locPoint = locPoint;
    
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    
    //创建路径
    UIBezierPath *path = [UIBezierPath bezierPath];
    
    [path moveToPoint:self.locPoint];
    
    //获取触摸对象
    UITouch *touch = touches.anyObject;
    
    //获取当前的点
    CGPoint currentPoint = [touch locationInView:touch.view];
    
    [path addLineToPoint:currentPoint];
    
    self.path = path;
    //重绘
    [self setNeedsDisplay];

}
- (void)drawRect:(CGRect)rect {
    
    [self.path stroke];
    
}

效果: 当点击屏幕不松手后,移动位置,绘制出一条从最初触摸屏幕时的点到最后停止时的点的一条直线

绘图-三种线样式_第1张图片
singleStraightLine.png

2 绘制多条直线

代码部分基本一致,只是路径从touchesBegan中创建换成了懒加载的方式

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    //创建触摸对象
    UITouch *touch = touches.anyObject;
    
    //获取最初的点
    CGPoint locPoint = [touch locationInView:touch.view];

    //赋值
    self.locPoint = locPoint;
    
}

- (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];
    
}
- (UIBezierPath *)path{

    if (!_path) {
        _path = [UIBezierPath bezierPath];
    }
    return _path;
}

实现效果图:

绘图-三种线样式_第2张图片
mulripleLInes.png

3.绘制触摸路径 代码和前两种几乎一致,同样只是路径的创建位置不同,实现的效果不同而已

不同点在于在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;
    
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    
    //获取触摸对象
    UITouch *touch = touches.anyObject;
    
    //获取当前的点
    CGPoint currentPoint = [touch locationInView:touch.view];

    //添加路径
    [self.path addLineToPoint:currentPoint];

    //重绘
    [self setNeedsDisplay];

}

实现效果图:

绘图-三种线样式_第3张图片
line.png

你可能感兴趣的:(绘图-三种线样式)