ios – Render CALayer on GPU


According to this answer by ldoogy, setting the drawsAsynchronously property of CALayer to true enables a Metal based renderer vastly improving performance.

This webpage affirms Idoogy’s claim.

However, I do not see any performance difference when drawsAsynchronously is set to true or false.

let layer = CALayer()
let drawsAsynchronously = true //Makes no difference set to true or false
shapeLayer.drawsAsynchronously = drawsAsynchronously

let f = CGRect(x: 0.0, y: 0.0, width: 1024.0, height: 1024.0)
let cgColor = UIColor.orange.cgColor

var lines: [CGPath] // populated with several hundred paths, some with hundreds of points

let start = CFAbsoluteTimeGetCurrent()
    
for path in lines {
    let pathLayer = CAShapeLayer()
    pathLayer.path = path
    pathLayer.strokeColor = cgColor
    pathLayer.fillColor = nil
    pathLayer.lineWidth = 1.0
    pathLayer.drawsAsynchronously = drawsAsynchronously
    layer.addSublayer(pathLayer)
}

UIGraphicsBeginImageContext(f.size)
let ctx = UIGraphicsGetCurrentContext()
layer.render(in: ctx!)
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()

//time: 0.05170309543609619
print("time: \(CFAbsoluteTimeGetCurrent() - start)")

Idoogy specifies renderInContext which is what I am using above. render(in:) has replaced renderInContext with modern Swift.

Surprisingly, UIGraphicsImageRenderer is much slower (nearly 300%), but also makes no difference if drawsAsynchronously is set to true or false:

let renderer = UIGraphicsImageRenderer(size: f.size)
let capturedImage = renderer.image { (ctx) in
    return layer.render(in: ctx.cgContext)
}

// time: 0.13654804229736328    
print("time: \(CFAbsoluteTimeGetCurrent() - start)")

Is there something I’ve missed to enable hardware accelerated rendering with drawsAsynchronously enabled?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img