欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

iOS 無卡頓同時(shí)使用圓角、陰影和邊框的實(shí)現(xiàn)

 更新時(shí)間:2020年01月13日 09:06:00   作者:LayoutBoy  
這篇文章主要介紹了iOS 無卡頓同時(shí)使用圓角、陰影和邊框的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

在 iOS 開發(fā)中,最怕看到設(shè)計(jì)稿里圓角、陰影和邊框同時(shí)出現(xiàn),這三兄弟簡(jiǎn)直就是性能殺手。

優(yōu)化的方法百度一下有很多,雖然方法不同但是原理都一樣。

分享一個(gè)我自己一直使用的方法:在一個(gè) View 里只應(yīng)用一種效果,然后通過組合的方式達(dá)到效果。

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
}

層次結(jié)構(gòu):

  • contentView: 描繪邊框,放在最上層。
  • imageView: 顯示圓角,放在中間,用于背景圖。
  • shadowView: 顯示陰影,放在最底層。代碼很簡(jiǎn)單,只是封裝了一下陰影參數(shù):
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
  }
}

分開單獨(dú)繪制速度很快,使用 UICollectionView 進(jìn)行滾動(dòng)測(cè)試,生成的 Cell 數(shù)量是 1 萬個(gè)。

測(cè)試機(jī)器是 5s + iOS 12.4.4,快速滑動(dòng)無任何卡頓。

給一個(gè)測(cè)試 demo 大家體驗(yàn)一下:

Github: shadow_view_demo

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論