Search code examples
calayerosx-elcapitancornerradius

CALayer cornerRadius + masksToBounds 10.11 glitch?


I have a 30x30 view which is rounded:

CALayer * layer = self.layer;
layer.backgroundColor = [NSColor redColor].CGColor;
layer.cornerRadius = 10.0f;
layer.masksToBounds = YES;

So far, so good: enter image description here

Then I add a sublayer, like so:

CALayer * subLayer = [CALayer layer];
subLayer.backgroundColor = [NSColor yellowColor].CGColor;
subLayer.frame = CGRectMake(0.0f, 0.0f, 10.0f, 10.0f);
[layer addSublayer:subLayer];

And I end up with this, which is not what I want! enter image description here

This is a problem that has only surfaced since my upgrade to El Capitan. In Yosemite the masking worked for the above code. What am I missing?

Update: this issue does not occur when I set layer.shouldRasterize = YES; however I want to keep memory down so I would prefer another solution.


Solution

  • I have found my own solution, using a shape layer + mask instead of cornerRadius:

    CALayer * layer = self.layer;
    layer.backgroundColor = [NSColor redColor].CGColor;
    //
    // code to replace layer.cornerRadius:
    CAShapeLayer * shapeLayer = [CAShapeLayer layer];
    float const r = 10.0f;
    float const w = self.bounds.size.width;
    float const h = self.bounds.size.height;
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, r, 0.0f);
    CGPathAddArcToPoint(path, NULL, w, 0.0f, w, r, r);
    CGPathAddArcToPoint(path, NULL, w, h, w - r, h, r);
    CGPathAddArcToPoint(path, NULL, 0.0f, h, 0.0f, h - r, r);
    CGPathAddArcToPoint(path, NULL, 0.0f, 0.0f, r, 0.0f, r);
    CGPathCloseSubpath ( path );
    shapeLayer.path = path;
    CGPathRelease(path);
    self.layer.mask = shapeLayer;
    //
    // add the sublayer
    CALayer * subLayer = [CALayer layer];
    subLayer.backgroundColor = [NSColor yellowColor].CGColor;
    subLayer.frame = CGRectMake(0.0f, 0.0f, 10.0f, 10.0f);
    [layer addSublayer:subLayer];
    

    Works as intended: enter image description here

    (Of course, if anyone has a more elegant fix, I'd love to see it!)