在 iOS 开发中,最怕看到设计稿里圆角、阴影和边框同时出现,这三兄弟简直就是性能杀手。 优化的方法百度一下有很多,虽然方法不同但是原理都一样。 分享一个我自己一直使用的方法:在一
在 iOS 开发中,最怕看到设计稿里圆角、阴影和边框同时出现,这三兄弟简直就是性能杀手。
优化的方法百度一下有很多,虽然方法不同但是原理都一样。
分享一个我自己一直使用的方法:在一个 View 里只应用一种效果,然后通过组合的方式达到效果。
override init(frame: CGRect) {
super.init(frame: frame)
imageView = UIImageView(image: UIImage(named: "img"))
imageView.layer.cornerRadius = 14
imageView.layer.masksToBounds = true
backgroundView = imageView
shadowView = ShadowView()
shadowView.layer.cornerRadius = 20
shadowView.applyShadow(.black, CGSize(width: 0, height: 15), 0.2, 40)
insertSubview(shadowView, belowSubview: imageView)
contentView.layer.cornerRadius = 14
contentView.layer.borderWidth = 1
contentView.layer.borderColor = UIColor.orange.cGColor
contentView.layer.masksToBounds = true
}
层次结构:
class ShadowView: UIView {
private var shadowColor: UIColor?
private var shadowOpacity: CGFloat = 1
private var shadowOffset: CGSize = CGSize(width: 0, height: 3)
private var shadowBlur: CGFloat = 6
override func layoutSubviews() {
super.layoutSubviews()
updateShadow()
}
func applyShadow(_ color: UIColor?, _ offset: CGSize, _ opacity: CGFloat, _ blur: CGFloat) {
shadowColor = color
shadowOffset = offset
shadowOpacity = opacity
shadowBlur = blur
updateShadow()
}
private func updateShadow() {
layer.shadowColor = shadowColor?.cgColor
layer.shadowOffset = shadowOffset
layer.shadowOpacity = Float(shadowOpacity)
layer.shadowRadius = shadowBlur * 0.5
layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: layer.cornerRadius).cgPath
}
}
分开单独绘制速度很快,使用 UICollectionView 进行滚动测试,生成的 Cell 数量是 1 万个。
测试机器是 5s + iOS 12.4.4,快速滑动无任何卡顿。
给一个测试 demo 大家体验一下:
--结束END--
本文标题: iOS 无卡顿同时使用圆角、阴影和边框的实现
本文链接: https://www.lsjlt.com/news/30413.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0