这可能比必要的要复杂,但是这里有一个解决方案。
使用以下方法扩展 UIView
:
extension UIView {
func dropShadow(superview: UIView) {
UIGraphicsBeginImageContext(self.bounds.size)
superview.drawViewHierarchyInRect(CGRect(x: -self.frame.minX, y: -self.frame.minY, width: superview.bounds.width, height: superview.bounds.height), afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageView = UIImageView(frame: self.bounds)
imageView.image = image
imageView.layer.cornerRadius = self.layer.cornerRadius
imageView.clipsToBounds = true
self.addSubview(imageView)
let brighter = UIView(frame: self.bounds)
brighter.backgroundColor = self.backgroundColor ?? UIColor(white: 1, alpha: 0.2)
brighter.layer.cornerRadius = self.layer.cornerRadius
brighter.clipsToBounds = true
self.addSubview(brighter)
self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.darkGrayColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 5)
self.layer.shadowOpacity = 0.35
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).CGPath
}
}
如果背景视图被命名为view
,那么使用如下:
let shadowView = UIView(frame: CGRect(x: 100, y: 100, width: 300, height: 200))
shadowView.layer.cornerRadius = 15.0
shadowView.dropShadow(view)
view.addSubview(shadowView)
这将导致视图呈现如下所示:
![UIView](https://istack.dev59.com/zJWfw.webp)
注意:由于这会导致图形上下文出现问题,因此不能在
viewDidLoad
中调用
dropShadow
方法。因此,请尽早在
viewWillAppear
中使用此方法以获得上述结果。
下面是背景视图的代码,以防有人想要在playgrounds中测试:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 400))
view.backgroundColor = UIColor.clearColor()
let color1 = UIColor(hue: 0.39, saturation: 0.7, brightness: 1.0, alpha: 1.0).CGColor
let color2 = UIColor(hue: 0.51, saturation: 0.9, brightness: 0.6, alpha: 1.0).CGColor
let gradient = CAGradientLayer()
gradient.frame = view.frame
gradient.colors = [color1, color2]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
view.layer.insertSublayer(gradient, atIndex: 0)