gpt4 book ai didi

ios - UIView 带有圆角和阴影?

转载 作者:行者123 更新时间:2023-11-30 11:52:42 26 4
gpt4 key购买 nike

我已经开发一个应用程序几年了,收到了一个简单的设计请求:圆化 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com