开发者

drawLayer not called when subclassing CALayer

I have a simple CALayer subclass (BoxLayer) with this drawLayer method:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    NSLog(@"drawLayer");
    NSGraphicsContext *nsGraphicsContext;
    nsGraphicsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx
                                                                   flipped:NO];
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext:nsGraphicsContext];

    // ...Draw content using NS APIs...
    NSPoint origin = { 21,21 };

    NSRect rect;
    rect.origin = origin;
    rect.size.width  = 128;
    rect.size.height = 128;

    NSBezierPath * path;
    path = [NSBezierPath bezierPathWithRect:rect];

    [path setLineWidth:4];

    [[NSColor whiteColor] set];
    [path fill];

    [[NSColor grayColor] set]; 
    [path stroke];

    [NSGraphicsContext restoreGraphicsState];
}

I then have this awakeFromNib in my NSView subclass:

- (void)awakeFromNib {
    CALayer* rootLayer = [CALayer layer];
    [self setLayer:rootLayer];
    [self 开发者_开发问答setWantsLayer:YES];

    box1 = [CALayer layer];
    box1.bounds = CGRectMake(0, 0, 70, 30);
    box1.position = CGPointMake(80, 80);
    box1.cornerRadius = 10;
    box1.borderColor = CGColorCreateGenericRGB(255, 0, 0, 1);
    box1.borderWidth = 1.5;
    [rootLayer addSublayer:box1];

    box2 = [BoxLayer layer];
    [box2 setDelegate:box2];
    [box2 setNeedsDisplay];
    [rootLayer addSublayer:box2];
}

My drawLayer is never called though, but why not?

Thank you


Possibly because the frame of your layer seems to be equal to CGRectZero, so the OS might think it's invisible so it doesn't need to draw it.

On a side note, why are going the complicated way of setting the layer's delegate to itself and implementing drawLayer:inContext: instead of using drawInContext: directly?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜