2011-06-04 55 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