在 iOS 開(kāi)發(fā)中,最怕看到設(shè)計(jì)稿里圓角、陰影和邊框同時(shí)出現(xiàn),這三兄弟簡(jiǎn)直就是性能殺手。
優(yōu)化的方法百度一下有很多,雖然方法不同但是原理都一樣。
分享一個(gè)我自己一直使用的方法:在一個(gè) View 里只應(yīng)用一種效果,然后通過(guò)組合的方式達(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):
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 }}分開(kāi)單獨(dú)繪制速度很快,使用 UICollectionView 進(jìn)行滾動(dòng)測(cè)試,生成的 Cell 數(shù)量是 1 萬(wàn)個(gè)。
測(cè)試機(jī)器是 5s + iOS 12.4.4,快速滑動(dòng)無(wú)任何卡頓。
給一個(gè)測(cè)試 demo 大家體驗(yàn)一下:
Github: shadow_view_demo
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選