【问题标题】:Improve Performance of Gradient Border using CAShapeLayer and CAGradientLayer使用 CAShapeLayer 和 CAGradientLayer 提高渐变边界的性能
【发布时间】:2016-03-08 02:26:42
【问题描述】:

我正在使用这种方法将渐变边框应用于视图。但是当视图位于 tableview 的单元格中时,table view 的滚动帧速率会显着下降。有没有办法提高性能?我尝试按照 Apple 的建议将 opaque 、 drawsAsynchronously 和 shouldRasterize 设置为 true ,但没​​有任何改变。

func addBorder(colors:[UIColor]? = nil,size:CGSize? = nil) {



    _ = self.sublayers?.filter({$0.name == "GradientBorder"}).map({$0.removeFromSuperlayer()})
    let shapeFrame = CGRect(origin: CGPointZero, size: size ?? bounds.size)
    let gradientLayer = CAGradientLayer()
    gradientLayer.name = "GradientBorder"

    gradientLayer.frame =  shapeFrame
    gradientLayer.startPoint = CGPointMake(0.0, 0.5)
    gradientLayer.endPoint = CGPointMake(1.0, 0.5)
    gradientLayer.colors = colors == nil ? [UIColor.blueColor().CGColor,UIColor.redColor().CGColor] : colors!.map({$0.CGColor})
    gradientLayer.contentsScale = UIScreen.mainScreen().scale


    let shapeLayer = CAShapeLayer()
    shapeLayer.lineWidth = 2

    shapeLayer.path = UIBezierPath(roundedRect: shapeFrame, cornerRadius: self.cornerRadius).CGPath
    shapeLayer.fillColor = nil
    shapeLayer.strokeColor = UIColor.blackColor().CGColor


    gradientLayer.shouldRasterize = true
    gradientLayer.opaque = true
    gradientLayer.drawsAsynchronously  = true
    shapeLayer.drawsAsynchronously  = true
    shapeLayer.opaque = true

    gradientLayer.mask = shapeLayer
    self.addSublayer(gradientLayer)



}

【问题讨论】:

  • 什么时候加边框?你能把那部分代码也展示一下吗?
  • @IBOutlet 弱变量 isOnlineViewContainer: UIView! { didSet { isOnlineViewContainer.layer.addBorder() } }
  • 嗯,我的意思是整个情况 - addBorder 函数多久调用一次?
  • 我有一个大约 50 个单元格的 collectionView。此 IBOutlet 位于 CollectionViewCell 类中。所以它被调用了大约 50 次。
  • 你确定每个单元格不会更频繁地调用它,例如当collectionview滚动时?

标签: ios swift uikit core-animation calayer


【解决方案1】:

好的,我找到了解决方案,而且非常简单。我只是简单地添加了这三行。

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    self.layer.shouldRasterize = true
    self.opaque = true
    self.layer.rasterizationScale = UIScreen.mainScreen().scale
}

【讨论】:

    猜你喜欢
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2017-01-20
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多