UIView的setNeedsDisplay和setNeedsLayout方法调用

来源:互联网 发布:linux如何安装xz 编辑:程序博客网 时间:2024/05/18 00:19

//以下都为转载文字:http://blog.csdn.net/diyagoanyhacker/article/details/7081072


首先两个方法都是异步执行的。而setNeedsDisplay会调用自动调用drawRect方法,这样可以拿到UIGraphicsGetCurrentContext,就可以画画了。而setNeedsLayout会默认调用layoutSubViews,就可以处理子视图中的一些数据。

宗上所诉,setNeedsDisplay方便绘图,而setNeedsLayout方便处理数据。

下面用setNeedsDisplay,实现涂鸦画板:

首先建立数组来存储触摸点信息:@property (nonatomic, strong) NSMutableArray *totalPathPoints;

- (NSMutableArray *)totalPathPoints
{
    if (_totalPathPoints == nil) {
        _totalPathPoints = [NSMutableArray array];
    }
    return _totalPathPoints;
}


//开始触摸记录起点
/**
 确定起点
 */
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint startPos = [touch locationInView:touch.view];
    
    // 每一次开始触摸, 就新建一个数组来存放这次触摸过程的所有点(这次触摸过程的路径)
    NSMutableArray *pathPoints = [NSMutableArray array];
    [pathPoints addObject:[NSValue valueWithCGPoint:startPos]];
    
    // 添加这次路径的所有点到大数组中
    [self.totalPathPoints addObject:pathPoints];
  
}


/**
 连线
 */
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint pos = [touch locationInView:touch.view];
    
    // 取出这次路径对应的数组
    NSMutableArray *pathPoints = [self.totalPathPoints lastObject];
    [pathPoints addObject:[NSValue valueWithCGPoint:pos]];
    //setNeedsDisplay默认调用drawRect:方法
    [self setNeedsDisplay];
}


- (void)drawRect:(CGRect)rect
{

//用图形上下文实现触摸涂鸦
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    for (NSMutableArray *pathPoints in self.totalPathPoints) {
        for (int i = 0; i<pathPoints.count; i++) { // 一条路径
            CGPoint pos = [pathPoints[i] CGPointValue];
            if (i == 0) {
                CGContextMoveToPoint(ctx, pos.x, pos.y);
            } else {
                CGContextAddLineToPoint(ctx, pos.x, pos.y);
            }
        }
    }
    

// 线边冒的三种类型:// CGLineCap.  kCGLineCapRound, kCGLineCapSquare,kCGLineCapButt后面两种差别不明显,感觉都是直角
    CGContextSetLineCap(ctx, kCGLineCapRound);

// 线段拐角出设置的三种类型// CGLineJoin. kCGLineJoinMiter(直角), kCGLineJoinRound(圆角), kCGLineJoinBevel(平角)
    CGContextSetLineJoin(ctx, kCGLineJoinRound);
    CGContextSetLineWidth(ctx, 5);
    CGContextStrokePath(ctx);
}



0 0