ios - 带有圆角和投影的 UIView?

标签 ios cocoa-touch uiview calayer rounded-corners

我已经在一个应用程序上工作了几年,并收到了一个简单的设计请求:在 UIView 上圆角并添加阴影。按照下面的说明进行操作。

我想要一个自定义的 UIView...:我只想要一个带有圆角和浅色阴影(没有灯光效果)的空白 View 。我可以一个接一个地执行这些操作,但通常会发生 clipToBounds/maskToBounds 冲突。

enter image description here

最佳答案

swift

enter image description here

// 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

探索选项

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

问题 1:阴影被剪掉

如果有子层或 subview (如图像)的内容我们想要裁剪到我们 View 的边界怎么办?

enter image description here

我们可以用

blueView.layer.masksToBounds = true

(或者,blueView.clipsToBounds = true 给出 same result。)

enter image description here

但是,哦不!阴影也被剪掉了,因为它在边界之外!该怎么办?怎么办?

解决方案

对阴影和边框使用单独的 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)

结果如下:

enter image description here

问题2:性能不佳

添加圆角和阴影可能会影响性能。您可以通过为阴影使用预定义路径并指定对其进行光栅化来提高性能。可以在上面的示例中添加以下代码。

baseView.layer.shadowPath = UIBezierPath(roundedRect: baseView.bounds, cornerRadius: 10).cgPath
baseView.layer.shouldRasterize = true
baseView.layer.rasterizationScale = UIScreen.main.scale

参见 this post更多细节。参见 herehere还有。

此答案已使用 Swift 4 和 Xcode 9 进行测试。

关于ios - 带有圆角和投影的 UIView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38648229/

相关文章:

ios - Objective-C中位掩码的使用 : how iOS handles options stored in bitmasks?

objective-c - presentModalViewController 不显示 naviagionbar

ios - 查找顶部显示的 View UIActionSheet

ios - UILabel 未显示在自定义 UIView 屏幕中

ios - UIKit 方法中的 "animated" bool 参数是否与设置动画持续时间不同?

iphone - View 的框架和 View 的绑定(bind)之间的区别 + iPhone

ios - 生成大型 PDF 时如何降低内存爬升

ios - 从 TableView 中删除行时 CoreData 应用程序崩溃

ios - 获取调用的 JSON 函数时复制数据

ios - 具有自动布局和部分重新加载的 UITableViewHeaderFooterView 子类不能很好地协同工作