Skip to content

Instantly share code, notes, and snippets.

@ksm
Created February 14, 2012 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksm/1830868 to your computer and use it in GitHub Desktop.
Save ksm/1830868 to your computer and use it in GitHub Desktop.
DrawView with a block for drawRect: an alternative to subclassing UIView for simple drawing operations
/*
Copied and pasted from David Hamrick's blog.
Source: http://www.davidhamrick.com/2011/08/07/using-blocks-for-drawing-to-avoid-subclasssing-in-objective-c.html
*/
typedef void(^DrawView_DrawBlock)(UIView* v,CGContextRef context);
@interface DrawView : UIView
@property (nonatomic,copy) DrawableView_DrawBlock drawBlock;
@end
/*
Copied and pasted from David Hamrick's blog.
Source: http://www.davidhamrick.com/2011/08/07/using-blocks-for-drawing-to-avoid-subclasssing-in-objective-c.html
*/
#import "DrawView.h"
@implementation DrawView
@synthesize drawBlock;
- (void)dealloc {
[drawBlock release], drawBlock = nil;
[super dealloc];
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
if(self.drawBlock)
self.drawBlock(self,context);
}
@end
@ksm
Copy link
Author

ksm commented Feb 14, 2012

Example usage:

/*
Copied and pasted from David Hamrick's blog. 

Source: http://www.davidhamrick.com/2011/08/07/using-blocks-for-drawing-to-avoid-subclasssing-in-objective-c.html
*/

DrawView* drawableView = [[[DrawView alloc] initWithFrame:CGRectMake(0,0,320,50)] 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);
    CGContextMoveToPoint(context, startPoint.x + 0.5, startPoint.y + 0.5);
    CGContextAddLineToPoint(context, endPoint.x + 0.5, endPoint.y + 0.5);
    CGContextStrokePath(context);
};
[self.view addSubview:drawableView];

@huytd
Copy link

huytd commented Aug 28, 2013

This line:
@Property (nonatomic,copy) DrawableView_DrawBlock drawBlock;

must be changed to:
@Property (nonatomic,copy) DrawView_DrawBlock drawBlock;

to work :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment