Last active
December 11, 2015 21:29
-
-
Save swissmanu/4663178 to your computer and use it in GitHub Desktop.
A global helper function to draw a vertical gradient using CoreGraphics. Pass a NSArray with UIColors and a plain C-array with step-location for each color. Don't invoke too often and when, don't use to many color steps. Each color needs to be converted using an expensive for-iteration.
This file contains 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
// NSArray *colors = @[[UIColor redColor], [UIColor greenColor], [UIColor blueColor]]; | |
// CGFloat locations[] = {0,.5,1}; | |
// DrawVerticalGradient(rect, colors, locations, ctx); | |
void DrawVerticalGradient(CGRect rect, NSArray* colors, const CGFloat steps[], CGContextRef ctx) { | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); | |
NSMutableArray *cgColors = [NSMutableArray arrayWithCapacity:colors.count]; | |
for (UIColor *color in colors) { | |
[cgColors addObject:(__bridge id)(color.CGColor)]; | |
} | |
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)cgColors, steps); | |
CGContextSaveGState(ctx); | |
CGContextAddRect(ctx, rect); | |
CGContextClip(ctx); | |
CGContextDrawLinearGradient(ctx, gradient, CGPointMake(0, rect.size.height), CGPointMake(0, 0),0); | |
CGContextRestoreGState(ctx); | |
CGGradientRelease(gradient); | |
CGColorSpaceRelease(colorSpace); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment