2011-06-04 56 views
0

我有一個UIView類,我正在使用CALayer。基於觸摸,此圖層將用於繪製線條。iPhone - 試圖在CALayer上畫線

這是類是如何定義的:

- (id)initWithFrame:(CGRect)frame { 

    self = [super initWithFrame:frame]; 
    if (self == nil) { 
     return nil; 
    } 

    self.layer.backgroundColor = [UIColor redColor].CGColor; 
    self.userInteractionEnabled = YES; 
    path = CGPathCreateMutable(); 
    return self; 
} 

然後我對的touchesBegan,TouchesMoved和touchesEnded以下行...

**touchesBegan** 
CGPathMoveToPoint(path, NULL, currentPoint.x, currentPoint.y); 
[self.layer setNeedsDisplay]; 


**touchesMoved** 
CGPathAddLineToPoint(path, NULL, currentPoint.x, currentPoint.y); 
[self.layer setNeedsDisplay]; 


**touchesEnded** 
CGPathAddLineToPoint(path, NULL, currentPoint.x, currentPoint.y); 
[self.layer setNeedsDisplay]; 

然後我有這個

-(void)drawInContext:(CGContextRef)context { 
    CGContextSetStrokeColorWithColor(context, [[UIColor greenColor] CGColor]); 
    CGContextSetLineWidth(context, 3.0); 
    CGContextBeginPath(context); 
    CGContextAddPath(context, path); 
    CGContextStrokePath(context); 
} 

touchesBegan/Moved/Ended方法被調用,但這個drawInContext方法永遠不會被調用d ...

我失蹤了什麼?

謝謝。

回答

6

當你可以很容易地使用UIKit API時,你正在混合圖層和視圖,並使用CG API。

在你的init方法中做到這一點;

- (id)initWithFrame:(CGRect)frame { 

    self = [super initWithFrame:frame]; 
    if (self == nil) { 
     return nil; 
    } 

    self.backgroundColor = [UIColor redColor]; 
    // YES is the default for UIView, only UIImageView defaults to NO 
    //self.userInteractionEnabled = YES; 
    [self setPath:[UIBezierPath bezierPath]]; 
    [[self path] setLineWidth:3.0]; 
    return self; 
} 

在您的事件處理代碼中;

**touchesBegan** 
[[self path] moveToPoint:currentPoint]; 
[self setNeedsDisplay]; 


**touchesMoved** 
[[self path] addLineToPoint:currentPoint]; 
[self setNeedsDisplay]; 


**touchesEnded** 
[[self path] addLineToPoint:currentPoint]; 
[self setNeedsDisplay]; 

然後執行drawRect:這樣;

- (void)drawRect:(CGRect)rect { 
     [[UIColor greenColor] setStroke]; 
     [[self path] stroke]; 
    } 

我從記憶中鍵入這,所以它可能無法編譯,它可能會重新格式化您的硬盤或來自火星的侵略者叫入侵你的家。好吧,也許不是那個......

該視圖是圖層的委託,所以如果你命名了你的繪圖方法drawLayer:inContext:你會得到什麼。但不要這樣做,做我以上所示。大多數情況下,你不應該考慮圖層。

+0

男人,你是一個天才!我已更正您的答案中的錯字,現在它正在完美工作。謝謝!!!! – SpaceDog 2011-06-04 04:56:53