UIView的setNeedsDisplay和setNeedsLayout方法調用

//以下都爲轉載文字: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);
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章