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];
        }
    
    }
  • 相关阅读:
    Git 分支开发规范
    小程序技术调研
    弹性布局
    vue 自定义指令的魅力
    记一次基于 mpvue 的小程序开发及上线实战
    mpvue学习笔记-之微信小程序数据请求封装
    微信小程序开发框架 Wepy 的使用
    Hbuilder 开发微信小程序的代码高亮
    luogu3807 【模板】 卢卡斯定理
    luogu1955 [NOI2015] 程序自动分析
  • 原文地址:https://www.cnblogs.com/znycat/p/4521017.html
Copyright © 2011-2022 走看看