简体   繁体   中英

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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