How to create new image just with gradient colors, using \"from-color\" and \"to-color\"?
Here's how I implemented Simon's suggestion (elsewhere in this thread) to create a reusable "hot" and "cold" UIImage like below:
Objective-C code:
-(UIImage*)createHotOrColdImage:(BOOL)bHot
{
// Create a UIImage with either a "Hot" or "Cold" gradient background
//
const int WIDTH = 75;
const int HEIGHT = 44;
// Do we want our UIImage to fade from black-to-red or black-to-blue ?
UIColor* color = (bHot) ? [UIColor redColor] : [UIColor colorWithRed:0.3 green:0.3 blue:1.0 alpha:1.0];
CGSize size = CGSizeMake(WIDTH, HEIGHT);
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
const CGFloat *components = CGColorGetComponents(color.CGColor);
CGFloat red = components[0];
CGFloat green = components[1];
CGFloat blue = components[2];
size_t gradientNumberOfLocations = 4;
CGFloat gradientLocations[4] = { 0.0, 0.3, 0.7, 1.0 };
CGFloat gradientComponents[16] = { red, green, blue, 0,
red, green, blue, 1,
red, green, blue, 1,
red, green, blue, 0 };
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents (colorspace, gradientComponents, gradientLocations, gradientNumberOfLocations);
// Create a UIImage containing this gradient
CGContextRef context = UIGraphicsGetCurrentContext();
// Make sure the gradient is vertical
CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(0, HEIGHT), 0);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(gradient);
CGColorSpaceRelease(colorspace);
UIGraphicsEndImageContext();
return image;
}
To use:
UIImage* hotImage = [self createHotOrColdImage:TRUE];
UIImage* coldImage = [self createHotOrColdImage:FALSE];