我已经开发一个应用程序几年了,收到了一个简单的设计请求:圆化 UIView 的角并添加阴影。按照下面给出的操作。
我想要一个自定义的UIView
...:我只想要一个带有圆角和浅色阴影(没有照明效果)的空白白色 View 。我可以一一完成这些操作,但通常会发生 clipToBounds
/maskToBounds
冲突。
最佳答案
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:阴影被剪掉
如果我们想要将子图层或 subview (如图像)的内容剪切到 View 的边界怎么办?
我们可以通过
来实现这一点blueView.layer.masksToBounds = true
(或者,blueView.clipsToBounds = true
给出 same result 。)
但是,哦不!阴影也被剪掉了,因为它超出了边界!该怎么办?该怎么办?
解决方案
对阴影和边框使用单独的 View 。基础 View 是透明的并且有阴影。边框 View 将它所具有的任何其他子内容剪切到其边框。
// 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
参见this post更多细节。请参阅here和 here还有。
此答案已使用 Swift 4 和 Xcode 9 进行了测试。
关于ios - UIView 带有圆角和阴影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48172249/