Skip to content

Instantly share code, notes, and snippets.

@dblock
Created April 23, 2014 20:59
Show Gist options
  • Save dblock/11232192 to your computer and use it in GitHub Desktop.
Save dblock/11232192 to your computer and use it in GitHub Desktop.
drawGradientImageFromColor
#import <Foundation/Foundation.h>
...
- (UIImage *)drawGradientImageFromColor:(UIColor *)beginColor toColor:(UIColor *)endColor imageSize:(CGSize)imageSize
{
// set sideline width
CGFloat lineWidth = 3.0f;
// set a canvas, and use the imageSize
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
// set RGB color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// set draw context
CGContextRef context = UIGraphicsGetCurrentContext();
// set color to array
NSArray *gradientColors = [NSArray arrayWithObjects:(id) beginColor.CGColor, (id) endColor.CGColor, nil];
// set range 0~1
// two value, cause two color
// if more color, add more value
CGFloat gradientLocation[] = { 0, 1 };
// set gradient info
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocation);
// set rectangle path for bezier path
UIBezierPath * bezierPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
CGContextSaveGState(context);
[bezierPath addClip];
// set gradient start point and end point
CGPoint beginPoint = CGPointMake(imageSize.width / 2, 0);
CGPoint endPoint = CGPointMake(imageSize.width / 2, imageSize.height);
// add position to linear gradient
CGContextDrawLinearGradient(context, gradient, beginPoint, endPoint, 0);
// set sideline info
CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
// draw sideline
[bezierPath setLineWidth:lineWidth];
// fill gradient color
[bezierPath stroke];
CGContextRestoreGState(context);
// output context to image
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
// context end and release
UIGraphicsEndImageContext();
CGColorSpaceRelease(colorSpace);
CGGradientRelease(gradient);
return image;
}
@dblock
Copy link
Author

dblock commented Apr 23, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment