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;
}
@end

@implementation CustomView

-(void)invalidate:(BOOL)async
{
    CGSize size = self.bounds.size;
    if(async)
    { 
        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;
           });

        }];
    }
    else
    {
        self.image = [self draw:size];

    }
}

-(UIImage*)draw:(CGSize)size
{
    CGFloat screenScale = [UIScreen mainScreen].scale;
    UIGraphicsBeginImageContextWithOptions(size, NO, screenScale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // Todo - Drawing code goes here

   UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   return image;
}


@end

Thats it!

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

Whenever you call invalidate you can draw out your view.

Enjoy!

By Stephen Zaharuk (SteveZ)