zoukankan      html  css  js  c++  java
  • 猫猫学IOS(三十四)UI之Quartz2D画画板的实现

    猫猫分享,必须精品

    原创文章,欢迎转载。转载请注明:翟乃玉的博客
    地址:http://blog.csdn.net/u013357243?viewmode=contents
    源码:http://blog.csdn.net/u013357243/article/details/45533403

    效果:

    这里写图片描述

    实现过程:

    首先用storyboard搭建界面,没有什么好说的。
    然后就是注意的功能了,这里用了触摸事件来搭配Quartz2D的路径来画画。
    思路就是把路径放到数组中

    @property (nonatomic, strong) NSMutableArray *paths;

    这里注意 如果用c语言的这个方式

    CGMutablePathRef path = CGPathCreateMutable();
         CGPathMoveToPoint(path, NULL, 20, 20);
         CGPathAddLineToPoint(path, NULL, 100, 100);

    画的话,是不能放到oc的数组中的,所以用了UIBezierPath创建一个路径对象。

    UIBezierPath *path = [UIBezierPath bezierPath];

    然后就是把路径放到数组中,渲染

    注意:刚刚开始我没有调用重绘方法,然后悲剧了,啥都没有。郁闷老半天。
    重绘:
    调用drawRect方法重回视图

    [self setNeedsDisplay];
    

    代码实现

    开始触摸:

    // 开始触摸
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
    
        // 1.获取手指对应UITouch对象
        UITouch *touch = [touches anyObject];
        // 2.通过UITouch对象获取手指触摸的位置
        CGPoint startPoint = [touch locationInView:touch.view];
    
        // 3.当用户手指按下的时候创建一条路径
        UIBezierPath *path = [UIBezierPath bezierPath];
        // 3.1设置路径的相关属性
        [path setLineJoinStyle:kCGLineJoinRound];
        [path setLineCapStyle:kCGLineCapRound];
        [path setLineWidth:10];
    
    
        // 4.设置当前路径的起点
        [path moveToPoint:startPoint];
        // 5.将路径添加到数组中
        [self.paths addObject:path];
    
    }
    

    移动:

    // 移动
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {
        // 1.获取手指对应UITouch对象
        UITouch *touch = [touches anyObject];
        // 2.通过UITouch对象获取手指触摸的位置
        CGPoint movePoint = [touch locationInView:touch.view];
    
        // 3.取出当前的path
        UIBezierPath *currentPaht = [self.paths lastObject];
        // 4.设置当前路径的终点
        [currentPaht addLineToPoint:movePoint];
    
        // 6.调用drawRect方法重回视图
        [self setNeedsDisplay];
    
    }

    回退和清屏方法:

    - (void)clearView
    {
        [self.paths removeAllObjects];
        [self setNeedsDisplay];
    }
    - (void)backView
    {
        [self.paths removeLastObject];
        [self setNeedsDisplay];
    }
    

    画线方法就是遍历数组中的UIBezierPath对象来实现

    // 画线
    - (void)drawRect:(CGRect)rect
    {
    
        [[UIColor redColor] set];
        // 边路数组绘制所有的线段
        for (UIBezierPath *path in self.paths) {
            [path stroke];
        }
    
    }
  • 相关阅读:
    超级干货;Python优化之使用pandas读取和训练千万级数据
    「git」mac下git提交github代码
    「Linux+Django」uwsgi服务启动(start)停止(stop)重新装载(reload)
    「Linux+Django」Django+CentOs7+uwsgi+nginx部署网站记录
    「Linux」centos7安装mysql
    「Linux」centos7安装使用rar
    「Linux」centos7安装uWSGI
    「Linux」centos7更新python3.6后yum报错问题
    「Linux」centos7安装python
    「Linux」VMware安装centos7(一)
  • 原文地址:https://www.cnblogs.com/znycat/p/4521017.html
Copyright © 2011-2022 走看看