Nell’iperspazio con Rocket: il Framework Web di Rust!
Core Graphics on background threads
1. Core Graphics Threads
keeping your UI responsive
Glenn Marcus
Founder, Cliq Consulting
@cliqconsulting glenn@cliqconsulting.com
2. Who Am I?
• Glenn Marcus - Tech Exec / Programmer
• American living in São Paulo
• Founder of Cliq Consulting
@cliqconsulting glenn@cliqconsulting.com
3. Core Graphics
Why ? Challenges
• Custom rendering of • C based API
views
• Pixels, not points
• Render on background
threads • Extra state to manage
• Requires CoreText for
background rendering
@cliqconsulting glenn@cliqconsulting.com
5. Technique
1. Create a backing layer to draw into
2. On background thread, draw to layer
3. On main thread, draw layer into view
@cliqconsulting glenn@cliqconsulting.com
6. Create a Layer
// Get the scale of the device
CGFloat contentScale = [[UIScreen mainScreen] scale];
// Calculate the pixels based on scale
CGSize layerSize = CGSizeMake(
self.bounds.size.width * contentScale,
self.bounds.size.height * contentScale);
// Create the layer with the current graphics context
destLayer = CGLayerCreateWithContext(
UIGraphicsGetCurrentContext(),
layerSize, NULL);
// Get the resulting layer
destContext = CGLayerGetContext(destLayer);
// Scale the layer context to match points
CGContextScaleCTM(destContext, contentScale, contentScale);
@cliqconsulting glenn@cliqconsulting.com
7. Conditional drawRect
if (self.layerIsReady)
// Draw the layer into the view
CGContextDrawLayerInRect(
UIGraphicsGetCurrentContext(), rect, destLayer);
else
// Prepare the layer in the background
[self performSelectorInBackground:
@selector(drawInBackground) withObject:nil];
@cliqconsulting glenn@cliqconsulting.com
8. Draw to Layer
// Do your usual CG rendering, using the layer Context
...
CGContextMoveToPoint(destContext, ...
CGContextAddLineToPoint(destContext, ...
CGContextStrokePath(destContext);
...
// When done, call a method on main thread to refresh view
self.layerIsReady = YES;
[self performSelectorOnMainThread:
@selector(refreshImage)
withObject:nil waitUntilDone:NO];
@cliqconsulting glenn@cliqconsulting.com
9. Refresh View
// setNeedsDisplay will call drawRect on the next event loop
- (void)refreshImage;
{
[self setNeedsDisplay];
}
@cliqconsulting glenn@cliqconsulting.com