iPhone - 试图在CALayer上画一条线

时间:2011-06-04 03:42:41

标签: iphone calayer quartz-graphics

我有一个UIView类,我用它来拥有一个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方法...

我错过了什么?

感谢。

1 个答案:

答案 0 :(得分: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:,那么您的工作就会有效。但是不要那样做,做我上面展示的。在大多数情况下,您不必考虑图层。

相关问题