1

I am trying to draw a custom CALayer which is then added as a sublayer elsewhere. The custom CALayer class only has one variable:

float xScale = 0.5f;

And overrides the drawInContext: method:

    -(void) drawInContext:(CGContextRef)ctx {

        NSLog(@"Method called with xScale %f", xScale);

        CGContextSetFillColorWithColor(ctx, [NSColor redColor].CGColor);
        CGContextAddRect(ctx, CGRectMake(100 * xScale, 100, 50, 50));
        CGContextFillPath(ctx);
    }

To draw a red square on the screen. When the class is initialised in a NSView elsewhere with:

heartLayer = [[HeartCALayer alloc] init];
heartLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[self.layer addSublayer:heartLayer];
[heartLayer setNeedsDisplay];

The square is drawn in the correct place. However when I then ask the layer to redraw with

heartLayer.xScale = 1.0f;
[heartLayer setNeedsDisplay];

The drawInContext: method is called, and the xScale variable is updated, but the square doesn't change it's location. I don't know why the screen is not updating. Is it something to do with the CALayer being added as a sublayer? Is the graphics context invalid somehow? Is it related to the implicit animation of CALayers? I've searched everywhere and am at my wits end :(

Thanks, Kenneth


Sorry to answer my own question: perhaps you'll waste less time than me:

The problem was the implicit animation of the CALayer class. This is discussed in this thread.

I added the following override method to the custom CALayer class:

- (id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)key {
    return (id)[NSNull null];
}

and my square updated correctly.

Community
  • 1
  • 1

0 Answers0