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

相關文章
相關標籤/搜索