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)



}

Answers


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
}

Need Your Help

How to fetch milliseconds using date time?

ssrs-2008 reporting-services

I have a client who wants the execution time of a report to be shown on the base of their report. To accommodate them I've created a variable on the report (under report properties) called '