My name is Jake Marsh.
I'm a developer, designer, and writer.

Subscribed via Push Notifications. You can also subscribe via RSS or Twitter.

Subscribe via RSS or Twitter.

Subscribe via Push Notifications, RSS or Twitter.

▸ Using Blocks for Drawing

I'm absolutely in love with the technique David Hamrick lays out in this post.

Instead of subclassing UIView every time we need to draw something what if we were to have one subclass that allowed us to pass in a block that performed the drawing code. So I’ve created a class called DrawView that does exactly that. It also passes itself and the graphics context since that was going to be needed in every block’s implementation so including them as parameters reduced the amount of boiler plate code needed.

It's a pretty simple idea: you shouldn't need to subclass just to do a tiny bit of custom drawing. Now you don't have to. With David's simple DrawView class, you can do your drawing like this:

DrawView *drawableView = [[[DrawView alloc] initWithFrame:CGRectMake(0.0 ,0.0, 320.0, 50.0)] autorelease];

drawableView.drawBlock = ^(UIView* v,CGContextRef context)
    CGPoint startPoint = CGPointMake(0,v.bounds.size.height-1);
    CGPoint endPoint = CGPointMake(v.bounds.size.width,v.bounds.size.height-1);

    CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);
    CGContextSetLineWidth(context, 1.0);
    CGContextMoveToPoint(context, startPoint.x + 0.5, startPoint.y + 0.5);
    CGContextAddLineToPoint(context, endPoint.x + 0.5, endPoint.y + 0.5);

[self.view addSubview:drawableView];

I wouldn't be surprised to see something like this show up in a future update to UIKit. Apple is starting to use blocks everywhere. This is just good sense.

Vote on Hacker News