Reputation: 3749
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)
}
Upvotes: 2
Views: 546
Reputation: 3749
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
}
Upvotes: 3