[英]Shadow not appearing for UIView using CALayer
I have a subclassed UIView
loaded from a nib, and I cannot get a shadow to draw around it. 我有一个从笔尖加载的子类UIView
,我无法在它周围画一个阴影。 I'm trying to get a shadow to appear around the entire view for quite some time now. 我试图在整个视图周围出现一个阴影已经有一段时间了。 I elected to place it in it's own sublayer to simplify animating it later. 我选择将它放在它自己的子层中,以便以后简化动画。 Here's the code: 这是代码:
-(void)awakeFromNib
{
self.clipsToBounds = NO;
// set up the shadow layer
CALayer *shadow = [CALayer layer];
shadow.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, self.bounds.size.height);
shadow.shadowColor = [UIColor blueColor].CGColor;
shadow.shadowRadius = 15.0;
shadow.opacity = 1.0;
[self.layer addSublayer:shadow];
// I set this property so I have access to it later to more easily animate it.
self.shadowLayer = shadow;
}
When I NSLog
the shadowLayer
property, the coordinates and frame are correct. 当我NSLog
shadowLayer
属性时,坐标和框架是正确的。 It's matches the view it's backing. 它与它支持的视图相匹配。
I also set a border color and corner radius on self.layer
and it appears correctly. 我还在self.layer
上设置了边框颜色和角半径,它显示正确。 If I put the shadow on self.layer
it appears but it encompasses all the subviews of my parent UIView
. 如果我将阴影放在self.layer
它会出现,但它包含了我的父UIView
所有子视图。
Any help is greatly appreciated. 任何帮助是极大的赞赏。
Am assuming you have QuartzCore
imported. 假设您已导入QuartzCore
。 I think you need to set & create a border to the UIView
. 我认为你需要为UIView
设置和创建一个边框。 The way to use this [self roundedLayerWithShadow:yourView.layer radius:5.0f];
使用此方法[self roundedLayerWithShadow:yourView.layer radius:5.0f];
- (void)roundedLayerWithShadow:(CALayer *)viewLayer
radius:(float)r
{
[viewLayer setMasksToBounds:YES];
[viewLayer setCornerRadius:r];
[viewLayer setBorderColor:[RGB(180, 180, 180) CGColor]];
[viewLayer setBorderWidth:1.0f];
[viewLayer setShadowColor:[RGB(0, 0, 0) CGColor]];
[viewLayer setShadowOffset:CGSizeMake(0, 0)];
[viewLayer setShadowOpacity:1];
[viewLayer setShadowRadius:2.0];
return;
}
I struggled with the same, and it turns out you need to set shadowOpacity
to 1.0. 我一直在努力,结果你需要将shadowOpacity
设置为1.0。 In your code you accidentally use opacity
instead of shadowOpacity
. 在您的代码中,您不小心使用了opacity
而不是shadowOpacity
。 That's the same issue I had. 那是我遇到的同样问题。
In general, for the shadow to appear: 一般来说,为了出现阴影:
Swift 4.2. Swift 4.2。 example implementation: 示例实现:
let myCustomView = MyCustomView()
myCustomView.layer.shadowColor = UIColor.black.cgColor
myCustomView.layer.shadowOpacity = 0.15
myCustomView.layer.shadowRadius = 5
myCustomView.layer.masksToBounds = false
myCustomView.layer.shadowOffset = CGSize(width: 0, height: 2)
Aside from borderRadius
, your shadow
layer looks very much transparent. 除了borderRadius
之外,您的shadow
层看起来非常透明。 Therefore it will not drop any shadow on shadow.superlayer
. 因此它不会丢弃shadow.superlayer
上的任何阴影。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.