为CAShapeLayer添加阴影,使内部保持透明 [英] Add a shadow to CAShapeLayer, so that the inside remains transparent
问题描述
我想为一个路径添加一个发光效果,就像它们有焦点时的蓝色光晕(OS X)界面元素一样。
I want to add a glow effect to a path, like the blue glow around (OS X) interface elements when they have focus.
我使用的是CAShapeLayer a(矩形)路径:
I used a CAShapeLayer with a (rectangular) path:
self.borderLayer = [CAShapeLayer layer];
CGPathRef path = CGPathCreateWithRect(self.bounds, NULL);
[self.borderLayer setPath:path];
CGPathRelease(path);
最后,这给了我一个带有边框的透明UIView。 (在我的具体情况下,它是带有附加动画的虚线,但这对于这个特定问题无关紧要)
In the end this gives me a transparent UIView with a border around it. (In my concrete case it's a dashed line with an additional animation, but that doesn't matter for this particular question)
我玩了CALayer的阴影属性,但它们总是填满整个图层。
I played around with the shadow properties of CALayer, but they will always fill the whole layer.
self.borderLayer.shadowPath = self.borderLayer.path;
self.borderLayer.shouldRasterize = YES;
我想要的是只有UIViews周边线投下一个阴影,以便UIView的内部保持透明。
What I want is that only the UIViews surrounding line drops a shadow, so that the inside of the UIView remains transparent.
推荐答案
我遇到类似的问题,看到我内心的阴影想要而不是发光。我用两个CALayers解决了这个问题。一,在代码中,背景为'_bg'(在我的情况下为黑色,不透明度为0.55)和白色边框。代码'_shadow'中的另一层具有清晰的背景并添加了发光效果。 _bg是_shadow图层的子视图。以下是相关代码:
I was having similar problems seeing the shadow inside where I wanted it instead of a glow. I solved it by using two CALayers. One, in the code, '_bg' for the background ( in my case black with opacity of 0.55) and a white border. The other layer, in the code '_shadow', has a clear background and adds the glow effect. _bg is a subview of the _shadow layer. Here's the relevant code:
_bg = [CALayer layer];
_shadow = [CALayer layer];
[self.layer insertSublayer:_shadow atIndex:0];
[_shadow addSublayer:_bg];
_bg.frame = self.bounds;
_bg.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:.55].CGColor;
_bg.cornerRadius=20.0;
_bg.borderColor=[UIColor whiteColor].CGColor;
_bg.borderWidth=2.0;
_shadow.frame=self.bounds;
_shadow.masksToBounds=NO;
_shadow.backgroundColor = [UIColor clearColor].CGColor;
_shadow.cornerRadius=3.0;
_shadow.shadowRadius=3.0;
_shadow.shadowColor=[UIColor whiteColor].CGColor;
_shadow.shadowOpacity=0.6;
_shadow.shadowOffset=CGSizeMake(0.0, 0.0);
这篇关于为CAShapeLayer添加阴影,使内部保持透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!