我试着给那些层叠在一起的视图添加一个阴影,视图折叠允许看到其他视图中的内容,在这种情况下,我想保持view.clipsToBounds
,这样当视图折叠时,它们的内容就会被裁剪。
这似乎让我很难在图层中添加阴影,因为当我打开clipsToBounds
时,阴影也会被裁剪。
我一直在尝试操作view.frame
和view.bounds
,以便在框架中添加投影,但允许边界足够大以包含它,但是我在这方面没有运气。
这是我用来添加阴影的代码(这只在clipsToBounds
关闭的情况下有效,如下所示)
view.clipsToBounds = NO;
view.layer.shadowColor = [[UIColor blackColor] CGColor];
view.layer.shadowOffset = CGSizeMake(0,5);
view.layer.shadowOpacity = 0.5;
这里是一个屏幕截图的阴影被应用于顶部最亮的灰色层。希望这能给出一个想法,如果clipsToBounds
关闭,我的内容将如何重叠。
如何在我的UIView
中添加阴影并保持内容的剪裁?
编辑:只是想补充一下,我也尝试过使用带阴影的背景图像,这确实很好用,但是我仍然想知道最好的编码解决方案。
发布于 2014-12-12 21:45:39
Wasabii在Swift 2.3中的回答是:
let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.blackColor().CGColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.CGPath
在Swift 3/4/5中:
let shadowPath = UIBezierPath(rect: view.bounds)
view.layer.masksToBounds = false
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 0.5)
view.layer.shadowOpacity = 0.2
view.layer.shadowPath = shadowPath.cgPath
如果您正在使用AutoLayout,请将此代码放在layoutSubviews()中。
在SwiftUI中,这一切都要容易得多:
Color.yellow // or whatever your view
.shadow(radius: 3)
.frame(width: 200, height: 100)
发布于 2012-03-19 03:07:05
发布于 2017-04-06 23:41:47
您可以为UIView创建一个扩展,以便在设计编辑器中访问这些值
extension UIView{
@IBInspectable var shadowOffset: CGSize{
get{
return self.layer.shadowOffset
}
set{
self.layer.shadowOffset = newValue
}
}
@IBInspectable var shadowColor: UIColor{
get{
return UIColor(cgColor: self.layer.shadowColor!)
}
set{
self.layer.shadowColor = newValue.cgColor
}
}
@IBInspectable var shadowRadius: CGFloat{
get{
return self.layer.shadowRadius
}
set{
self.layer.shadowRadius = newValue
}
}
@IBInspectable var shadowOpacity: Float{
get{
return self.layer.shadowOpacity
}
set{
self.layer.shadowOpacity = newValue
}
}
}
https://stackoverflow.com/questions/9761189
复制相似问题