iOS - Async Drawing - Part 1

Stephen Zaharuk / Tuesday, December 15, 2015

In the world of App Development, performance is always a concern. Today, i'm going to show you how you can easily add performance to your application for custom drawing.

If you've ever used the CoreGraphics API's, then you probably know that the drawing work is done mainly on the CPU. Since, the rest of your Application logic is also going to be dependent on the CPU, you don't want your UI code to be locking it up. 

In this three part series I'm going to walk you through the code to set this up. 

Part 1: Drawing into an Image

Part 2: Using GCD

Part 3: Putting them together

Part 1: Drawing into an Image

Normally, when you go to draw some custom UI, you probably draw into the CGContext of a UIView. And while thats a legitimate way to do that, you have less control over when you can draw. 

Instead, by drawing into an Image, you have complete control, and even the added benefit of controlling the resolution of what you're drawing. 

So, what does the code look like for drawing into an Image. Well its surprisingly very simple:

    CGFloat screenScale = [UIScreen mainScreen].scale;
    UIGraphicsBeginImageContextWithOptions(size, NO, screenScale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // Todo - Drawing code goes here

    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();

    return image;

And thats it! Really simple, right?

Lets just walk through the snippet, so you know whats going on. 

The first part, grabbing the screenScale, controls the "pixel density" the image will be rendered. Basically if the image is retina, or non retina. By default, the scale will be 1 which is non retina. So, we grab the scale of the device and use that, so that it looks good no matter what device we're on. Note, the higher the scale, the worse the performance should be. So if you ever need to get better performance, and rendering quality is not as important, you can always lower the scale. 

The next steps, are just grabbing the CGContext that we're going to draw into. 

Then you can insert your drawing code. 

And finally, we need to grab the image we wanted to create. 

Stay tuned for part 2 in the series where i walk through the Async code. 

By Stephen Zaharuk (SteveZ)