Last active
August 29, 2015 14:02
-
-
Save mike3k/c537ebbe8274152ec53e to your computer and use it in GitHub Desktop.
This view draws a partially colored image as a pie chart based on two numeric values representing the total allowance and the current amount as a percentage of the total, using color and grayscale versions of an image.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* This view draws a partially colored image as a pie chart based on two numeric values | |
* representing the total allowance and the current amount as a percentage of the total, | |
* using color and grayscale versions of an image. | |
* | |
*/ | |
#define PI 3.14159265358979323846 | |
@interface ChartIconView: UIView | |
@property (nonatomic, strong) UIImage *colorImage; | |
@property (nonatomic, strong) UIImage *grayImage; | |
@property (nonatomic, assign) float currentAmount; | |
@property (nonatomic, assign) float totalAllowance; | |
@end | |
@implementation ChartIconView | |
@synthesize colorImage = _colorImage; | |
@synthesize grayImage = _grayImage; | |
@synthesize currentAmount = _currentAmount; | |
@synthesize totalAllowance = _totalAllowance; | |
static inline float radians(double degrees) { return degrees * PI / 180; } | |
- (void)drawRect:(CGRect)rect { | |
// Drawing code | |
CGRect parentViewBounds = self.bounds; | |
CGFloat x = CGRectGetWidth(parentViewBounds)/2; | |
CGFloat y = CGRectGetHeight(parentViewBounds)/2; | |
int radius = floor(x)+5; | |
float endpos = (_currentAmount < _totalAllowance) ? ((_currentAmount / _totalAllowance) * 360.0) : 360.0; | |
// Get the graphics context | |
CGContextRef ctx = UIGraphicsGetCurrentContext(); | |
CGContextSaveGState(ctx); | |
CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0); | |
CGContextFillRect(ctx, parentViewBounds); | |
CGContextTranslateCTM(ctx, 0, parentViewBounds.size.height); | |
CGContextScaleCTM(ctx, 1.0, -1.0); | |
CGContextDrawImage(ctx, parentViewBounds, _grayImage.CGImage); | |
CGContextMoveToPoint(ctx, x+2, y); | |
CGContextAddArc(ctx, x+2, y, radius, 0.0, radians(endpos), 0); | |
CGContextClosePath(ctx); | |
CGContextClip(ctx); | |
CGContextDrawImage(ctx, parentViewBounds, _colorImage.CGImage); | |
CGContextRestoreGState(ctx); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment