Skip to content

Instantly share code, notes, and snippets.

@jblocksom
Last active December 21, 2015 09:39
Show Gist options
  • Save jblocksom/6286571 to your computer and use it in GitHub Desktop.
Save jblocksom/6286571 to your computer and use it in GitHub Desktop.
Helpers for Quartz chapter
#define RANGE (700.0f)
// RANGE is the range of values that are OK
#define B_MARGIN (10.0f)
// B_MARGIN is the bottom margin in points
#define T_MARGIN (10.0f)
// T_MARGIN is the top margin in points
#define H_GAP (10.4f)
// H_GAP is the gap between the bars and side margins
- (id)initWithPersons:(NSArray *)persons
{
self = [super init];
if (self) {
self.persons = persons;
}
return self;
}
- (void)drawInContext:(CGContextRef)ctx
bounds:(CGRect)bounds
{
NSLog(@"Drawing in %@", NSStringFromCGRect(bounds));
CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
CGFloat blackRGBA[] = { 0, 0, 0, 1 };
CGColorRef black = CGColorCreate(cs, blackRGBA);
CGFloat whiteRGBA[] = { 1, 1, 1, 1 };
CGColorRef white = CGColorCreate(cs, whiteRGBA);
CGContextSetStrokeColorWithColor(ctx, black);
CGContextSetLineWidth(ctx, 1);
CGContextSetFillColorWithColor(ctx, white);
float minY = CGRectGetMinY(bounds) + B_MARGIN;
float maxY = CGRectGetMaxY(bounds) - T_MARGIN;
float increment = (maxY - minY) / RANGE;
int personCount = [self.persons count];
float totalHGaps = (personCount + 2) * H_GAP;
float barWidth = (bounds.size.width - totalHGaps) / personCount;
// Draw the bars
CGRect barRect;
barRect.size.width = barWidth;
barRect.origin.y = minY;
int idx=0;
for (BNRPerson *person in self.persons) {
barRect.origin.x = bounds.origin.x + H_GAP + (barWidth + H_GAP) * idx;
barRect.size.height = increment * person.sales;
CGPathRef barPath = CGPathCreateWithRect(barRect, NULL);
CGContextAddPath(ctx, barPath);
CGContextFillPath(ctx);
// Fill path clears the current path, so add it again
CGContextAddPath(ctx, barPath);
CGContextStrokePath(ctx);
CGPathRelease(barPath);
idx++;
}
CGColorRelease(white);
CGColorRelease(black);
CGColorSpaceRelease(cs);
}
- (void)drawLayer:(CALayer *)layer
inContext:(CGContextRef)ctx
{
[self drawInContext:ctx bounds:layer.bounds];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment