美文网首页iOS Developer
iOS使用对象上下文创建简易画板

iOS使用对象上下文创建简易画板

作者: 羊非鱼丶 | 来源:发表于2017-05-09 16:19 被阅读0次

    之前有写过一篇iOS使用贝塞尔曲线创建简易画板,可以跟这篇做一个对比。

    依然是先看效果:


    画板.gif

    原理跟iOS使用贝塞尔曲线创建简易画板中介绍的基本相同,不做详细说明了,直接上主要代码:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        UITouch *touch = [touches anyObject];
        
        CGPoint beginPoint = [touch locationInView:touch.view];
        
        NSMutableArray *subarray = [NSMutableArray array];
        [subarray addObject:[NSValue valueWithCGPoint:beginPoint]];
        [self.totalPathPoints addObject:subarray];
    }
    
    
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        [self drawLineWithTouches:touches];
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        [self drawLineWithTouches:touches];
    }
    
    
    - (void)drawLineWithTouches:(NSSet *)touches {
    
        UITouch *touch = [touches anyObject];
        
        CGPoint movePoint = [touch locationInView:touch.view];
        
        
        NSMutableArray *subarray = [self.totalPathPoints lastObject];
        
        [subarray addObject:[NSValue valueWithCGPoint:movePoint]];
        
        [self setNeedsDisplay];
    
    }
    
    

    在drawRect方法当中:

      CGContextRef ctx = UIGraphicsGetCurrentContext();
        
        
        for (NSMutableArray *arr in self.totalPathPoints) {
            for (int i = 0; i < arr.count; i++) {
                
                if (i == 0) {
                    CGPoint startPoint = [arr[i] CGPointValue];
                    CGContextMoveToPoint(ctx, startPoint.x, startPoint.y);
                    
                }
                else{
                    CGPoint movePoint = [arr[i] CGPointValue];
                    CGContextAddLineToPoint(ctx, movePoint.x, movePoint.y);
                }
            }
            
        }
        
        CGContextSetLineJoin(ctx, kCGLineJoinRound);
        CGContextSetLineCap(ctx, kCGLineCapRound);
        CGContextSetLineWidth(ctx, 5);
        
        CGContextStrokePath(ctx);
    
    

    这里放上demo

    相关文章

      网友评论

        本文标题:iOS使用对象上下文创建简易画板

        本文链接:https://www.haomeiwen.com/subject/hqqitxtx.html