CALayer cornerRadius + masksToBounds 10.11毛刺?

时间:2016-02-22 16:46:06

标签: calayer osx-elcapitan cornerradius

我有一个30x30的视图,它是四舍五入的:

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

到目前为止,非常好:enter image description here

然后我添加一个子图层,如下所示:

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

我最终得到了这个,这不是我想要的! enter image description here

这是一个问题,自我升级到El Capitan后才浮出水面。在Yosemite中,掩码适用于上述代码。我错过了什么?

更新:当我设置layer.shouldRasterize = YES;时不会发生此问题但是我想保留内存,所以我更倾向于使用其他解决方案。

1 个答案:

答案 0 :(得分:0)

我找到了自己的解决方案,使用形状图层+蒙版而不是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];

按预期工作:enter image description here

(当然,如果有人有更优雅的解决方案,我很乐意看到它!)