简体   繁体   English

使用CAShapeLayer和CAGradientLayer改善渐变边框的性能

[英]Improve Performance of Gradient Border using CAShapeLayer and CAGradientLayer

I am using this method to apply gradient border to views. 我正在使用此方法将渐变边框应用于视图。 But when the view is in a cell of a tableview, the scrolling frame rate of the table view drops significally. 但是,当视图位于表格视图的单元格中时,表格视图的滚动帧速率会显着下降。 Is there a way to improve the performance ? 有没有办法提高性能? I tried setting the opaque , drawsAsynchronously and shouldRasterize to true as Apple is suggesting but nothing changed. 我尝试将opaque,drawsAsynchronously设置为true,并且应该按照Apple的建议将true正确设置为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)



}

Ok i found the solution and it was very easy. 好的,我找到了解决方案,这非常容易。 I simply added these three lines. 我只是添加了这三行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM