当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS 无卡顿同时使用圆角、阴影和边框的实现

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

2020年03月09日  | 移动技术网IT编程  | 我要评论

薇丝露,鼎盛卡盟,农民创业史

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网