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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-04-02 我要评论

在 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
}

层次结构:

  • contentView: 描绘边框,放在最上层。
  • 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,快速滑动无任何卡顿。

给一个测试 demo 大家体验一下:

Github: shadow_view_demo

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们