绘图-三种线样式

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 效果图:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • "小画板程序"完成"小画板"程序。 下载地址:http://git.oschina.net/changyou/my...
    _浅墨_阅读 3,987评论 0 5
  • Quartz2D以及drawRect的重绘机制字数1487 阅读21 评论1 喜欢1一、什么是Quartz2D Q...
    PurpleWind阅读 4,243评论 0 3
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 10,533评论 5 13
  • 绘制一条直线 1.1 声明全局属性,用来存放触摸屏幕时的初始坐标点和路径 说明: 因为在移动事件中创建路径,所...
    ShenYj阅读 3,150评论 0 1
  • -- iOS事件全面解析 概览 iPhone的成功很大一部分得益于它多点触摸的强大功能,乔布斯让人们认识到手机其实...
    翘楚iOS9阅读 8,155评论 0 13