iOS - Async Drawing - Part 3

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 3: Putting them together

Ok so by now you're able to render into an image, and you know how to create async code. So how do we put the 2 together?

It's actually very simple. 

We're going to first create a new View, but derive from UIImageView. 

Then we're going to add an invalidate method with a flag that says whether or not render async. 

And thats basically it!

@interface CustomView()
    SingleDispatchQueue* _dispatcher;

@implementation CustomView

    CGSize size = self.bounds.size;
        if(_dispatcher == nil)
            _dispatcher = [[SingleDispatchQueue alloc]init];

        __weak CustomView* weakSelf = self;
        [_dispatcher addBlock:^()
            UIImage* image = [weakSelf draw:size];
            dispatch_sync(dispatch_get_main_queue(), ^()
               weakSelf.image = image;

        self.image = [self draw:size];


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

    // Todo - Drawing code goes here

   UIImage* image = UIGraphicsGetImageFromCurrentImageContext();

   return image;


Thats it!

Now just insert your drawing code, and you're good to go. 

Whenever you call invalidate you can draw out your view.


By Stephen Zaharuk (SteveZ)