Swift
// corner radius
blueView.layer.cornerRadius = 10
// border
blueView.layer.borderWidth = 1.0
blueView.layer.borderColor = UIColor.black.cgColor
// shadow
blueView.layer.shadowColor = UIColor.black.cgColor
blueView.layer.shadowOffset = CGSize(width: 3, height: 3)
blueView.layer.shadowOpacity = 0.7
blueView.layer.shadowRadius = 4.0
探索选项
问题 1:阴影被剪掉
如果我们想要将子图层或子视图(如图像)的内容剪切到视图的边界怎么办?
我们可以通过以下方式完成此任务
blueView.layer.masksToBounds = true
(或者,blueView.clipsToBounds = true
给出相同的结果 https://stackoverflow.com/a/1177978/3681880.)
But, oh no!阴影也被剪掉了,因为它超出了边界!该怎么办?该怎么办?
Solution
对阴影和边框使用单独的视图。基础视图是透明的并且有阴影。边框视图将它所具有的任何其他子内容剪切到其边框。
// add the shadow to the base view
baseView.backgroundColor = UIColor.clear
baseView.layer.shadowColor = UIColor.black.cgColor
baseView.layer.shadowOffset = CGSize(width: 3, height: 3)
baseView.layer.shadowOpacity = 0.7
baseView.layer.shadowRadius = 4.0
// add the border to subview
let borderView = UIView()
borderView.frame = baseView.bounds
borderView.layer.cornerRadius = 10
borderView.layer.borderColor = UIColor.black.cgColor
borderView.layer.borderWidth = 1.0
borderView.layer.masksToBounds = true
baseView.addSubview(borderView)
// add any other subcontent that you want clipped
let otherSubContent = UIImageView()
otherSubContent.image = UIImage(named: "lion")
otherSubContent.frame = borderView.bounds
borderView.addSubview(otherSubContent)
这给出了以下结果:
问题2:性能不佳
添加圆角和阴影可能会影响性能。您可以通过使用预定义的阴影路径并指定对其进行光栅化来提高性能。可以将以下代码添加到上面的示例中。
baseView.layer.shadowPath = UIBezierPath(roundedRect: baseView.bounds, cornerRadius: 10).cgPath
baseView.layer.shouldRasterize = true
baseView.layer.rasterizationScale = UIScreen.main.scale
See 这个帖子 http://kemal.co/index.php/2013/01/giving-shadow-to-a-rounded-corner-uiview/更多细节。看here http://damir.me/rounded-uiview-with-shadow-the-right-way and here https://coderchrismills.wordpress.com/2011/07/14/uiview-drop-shadow-with-rounded-corners/ also.
这个答案已经用 Swift 4 和 Xcode 9 进行了测试。