iOS 无卡顿同时使用圆角、阴影和边框

在 iOS 开发中,最怕看到设计稿里圆角、阴影和边框同时出现,这三兄弟简直就是性能杀手。git

优化的方法百度一下有不少,虽然方法不一样可是原理都同样。github

分享一个我本身一直使用的方法:在一个 View 里只应用一种效果,而后经过组合的方式达到效果。swift

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
}
复制代码

层次结构:app

  • contentView: 描绘边框,放在最上层。ide

  • imageView: 显示圆角,放在中间,用于背景图。性能

  • shadowView: 显示阴影,放在最底层。代码很简单,只是封装了一下阴影参数:测试

    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,快速滑动无任何卡顿。ui

给一个测试 demo 你们体验一下:spa

Github: shadow_view_demo

相关文章
相关标签/搜索