zoukankan      html  css  js  c++  java
  • AJ学IOS(34)UI之Quartz2D画画板的实现

    AJ分享,必须精品

    效果:

    这里写图片描述

    实现过程:

    首先用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];
        }
    
    }
  • 相关阅读:
    Mybatis Cause: java.lang.ClassNotFoundException: Cannot find class:
    java常见面试题及部分答案
    页面css样式找不到问题
    深入分析Java I/O的工作机制 (二)
    深入分析Java I/O的工作机制 (一)
    LifecycleProcessor not initialized
    几个java小例子
    idea 过段时间java程序包不存在问题 ?
    使用HttpClient发送Get/Post请求 你get了吗?
    Convert PIL Image to byte array?
  • 原文地址:https://www.cnblogs.com/luolianxi/p/4990339.html
Copyright © 2011-2022 走看看