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

相关文章:

ios - 如何添加自定义tableviewcell分隔符?

ios - 没有使用 Objective-c 分配给属性 swift 3 的 setter 方法

iPad 上的 jQuery animate(向左滑动)...如何提高性能?

ios - ExpandableLable 仅适用于系统字体

iphone - 如何从嵌套的 UIViewController 中获取正确的 UIInterfaceOrientation

objective-c - 使用 CFDictionaryRef 和 A​​BMutableMultiValueRef 的无法解释的泄漏

iOS:默认的 segue 动画违反并破坏了我的其他动画时间

ios - Xcode-命令行构建

javascript - 将本地存储从 swift 注入(inject)到 WKWebview

ios - 通过 Interface Builder 更改 UIView 属性