Created
April 23, 2014 20:59
-
-
Save dblock/11232192 to your computer and use it in GitHub Desktop.
drawGradientImageFromColor
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
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://carlos-blog.logdown.com/posts/2013/09/14/ios-uiimage-with-gradient-color