-
Notifications
You must be signed in to change notification settings - Fork 55
/
YOBarChartImage.m
78 lines (62 loc) · 2.39 KB
/
YOBarChartImage.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#import "YOBarChartImage.h"
@implementation YOBarChartImage
- (instancetype)init
{
self = [super init];
if (self) {
_barStyle = YOBarChartImageBarStyleVertical;
_barPadding = 0.0;
_strokeWidth = 0.0;
_fillColor = [UIColor whiteColor];
_strokeColor = nil;
}
return self;
}
- (NSNumber *) maxValue {
return _maxValue ? _maxValue : [NSNumber numberWithFloat:[[_values valueForKeyPath:@"@max.floatValue"] floatValue]];
}
const CGFloat kBarPaddingMultipler = 20.0f;
- (UIImage *)drawImage:(CGRect)frame scale:(CGFloat)scale {
NSAssert(_values.count > 0, @"YOBarChartImage // must assign values property which is an array of NSNumber");
CGFloat maxValue = self.maxValue.floatValue;
CGFloat dataCount = (CGFloat)_values.count;
CGFloat padding;
if (_barPadding > 0.0f) {
padding = _barPadding;
} else {
padding = ceil(1.0f / dataCount * kBarPaddingMultipler);
}
CGFloat totalPadding = (dataCount - 1.0f) * padding;
CGFloat totalWidth = _barStyle == YOBarChartImageBarStyleVertical ? (frame.size.width - totalPadding) : (frame.size.height - totalPadding);
CGFloat barWidth = totalWidth / dataCount;
UIGraphicsBeginImageContextWithOptions(frame.size, false, scale);
[_values enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger idx, BOOL *_) {
CGFloat normalizedValue = number.floatValue / maxValue;
CGRect rect;
if (_barStyle == YOBarChartImageBarStyleVertical) {
rect = (CGRect) {
(CGFloat)idx * (barWidth + padding) + _strokeWidth / 2,
frame.size.height * (1.0 - normalizedValue) + _strokeWidth / 2,
barWidth - _strokeWidth,
frame.size.height / normalizedValue
};
} else {
rect = (CGRect) {
-_strokeWidth,
(CGFloat)idx * (barWidth + padding) + _strokeWidth / 2,
frame.size.width * normalizedValue + _strokeWidth / 2,
barWidth - _strokeWidth
};
}
UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect];
path.lineWidth = _strokeWidth;
[_fillColor setFill];
[path fill];
[_strokeColor setStroke];
[path stroke];
}];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end