Skip to content

Instantly share code, notes, and snippets.

@mikezs
Created January 29, 2013 13:30
Show Gist options
  • Save mikezs/4664251 to your computer and use it in GitHub Desktop.
Save mikezs/4664251 to your computer and use it in GitHub Desktop.
UIImage+CustomColours.h
@interface UIImage (CustomColours)
+ (UIImage *) imageWithLinearGradientOfSize:(CGSize)size start:(UIColor *)start end:(UIColor *)end;
+ (UIImage *) imageWithSolidColor:(UIColor *)color size:(CGSize)size;
@end
#import "UIImage+CustomColours.h"
@implementation UIImage (CustomColours)
+ (UIImage *) imageWithLinearGradientOfSize:(CGSize)size start:(UIColor *)start end:(UIColor *)end
{
// Initialise
UIGraphicsBeginImageContextWithOptions(size, YES, 1);
// Create the gradient's colours
CGFloat locations[2] = { 0.0, 1.0 };
CFArrayRef colors = (__bridge CFArrayRef) @[(id)start.CGColor, (id)end.CGColor];
CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef myGradient = CGGradientCreateWithColors (myColorspace, colors, locations);
CGPoint startPoint = CGPointMake(size.width / 2.0f, 0.0f);
CGPoint endPoint = CGPointMake(size.width / 2.0f, size.height);
// Do actual drawing
CGContextDrawLinearGradient(UIGraphicsGetCurrentContext(), myGradient, startPoint, endPoint, kCGGradientDrawsAfterEndLocation);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// Clean up
CGColorSpaceRelease(myColorspace); // Necessary?
CGGradientRelease(myGradient); // Necessary?
UIGraphicsEndImageContext(); // Clean up
return image;
}
+ (UIImage *) imageWithSolidColor:(UIColor *)color size:(CGSize)size
{
// Initialise
UIGraphicsBeginImageContextWithOptions(size, YES, 1);
// Set colour
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor);
// Do actual drawing
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width, size.height));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); // Clean up
return image;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment