Skip to content

Instantly share code, notes, and snippets.

@aspitz
Last active December 19, 2015 12:18
Show Gist options
  • Save aspitz/5953390 to your computer and use it in GitHub Desktop.
Save aspitz/5953390 to your computer and use it in GitHub Desktop.
A subclass of UIView that allows a developer to draw in a view without having to subclass UIView
typedef void (^DrawBlock)(CGContextRef currentContext, CGRect drawRect, UIView *selfView);
@interface ZDrawView : UIView
@property (nonatomic, copy) DrawBlock drawBlock;
- (instancetype)initWithBlock:(DrawBlock)block;
+ (instancetype)viewWithBlock:(DrawBlock)block;
+ (instancetype)horizontalLine;
+ (instancetype)horizontalLineWithColor:(UIColor *)lineColor;
+ (instancetype)verticalLine;
+ (instancetype)verticalLineWithColor:(UIColor *)lineColor;
- (void)drawRect:(CGRect)drawRect;
@end
@implementation ZDrawView
#pragma mark - Init methods
- (instancetype)initWithBlock:(DrawBlock)block{
self = [super init];
if (self){
self.drawBlock = block;
}
return self;
}
+ (instancetype)viewWithBlock:(DrawBlock)block{
return [[[self class]alloc]initWithBlock:block];
}
#pragma mark - Horizontal line methods
+ (instancetype)horizontalLine{
return [[self class]horizontalLineWithColor:[UIColor darkGrayColor]];
}
+ (instancetype)horizontalLineWithColor:(UIColor *)lineColor{
return [[[self class]alloc]initWithBlock:^(CGContextRef currentContext, CGRect drawRect, UIView *selfView) {
[lineColor setStroke];
CGContextMoveToPoint(currentContext, drawRect.origin.x, drawRect.origin.y);
CGContextAddLineToPoint(currentContext, drawRect.origin.x + drawRect.size.width, drawRect.origin.y);
CGContextStrokePath(currentContext);
}];
}
#pragma mark - Vertical line
+ (instancetype)verticalLine{
return [[self class]verticalLineWithColor:[UIColor darkGrayColor]];
}
+ (instancetype)verticalLineWithColor:(UIColor *)lineColor{
return [[[self class]alloc]initWithBlock:^(CGContextRef currentContext, CGRect drawRect, UIView *selfView) {
[lineColor setStroke];
CGContextMoveToPoint(currentContext, drawRect.origin.x, drawRect.origin.y);
CGContextAddLineToPoint(currentContext, drawRect.origin.x, drawRect.origin.y + drawRect.size.height);
CGContextStrokePath(currentContext);
}];
}
#pragma mark - drawRect method
- (void)drawRect:(CGRect)drawRect{
[super drawRect:drawRect];
if (self.drawBlock != nil){
self.drawBlock(UIGraphicsGetCurrentContext(), drawRect, self);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment