Gradient images look like very attractive, isn't it?
With this powerful Objective-C method creating an UIImage gradient image is too easy.
You need:
- http://objective-c-functions.blogspot.com/2013/06/helpful-color-struct-rgb-hsv.html
- http://objective-c-functions.blogspot.com/2013/06/get-rgba-components-of-uicolor.html
/** Returns a gradient image.
@param startColor Color to start from.
@param endColor Color to end to.
@param size Size of the result image.
@return Returns a new UIImage which is the result of gradient effect from two colors.
*/
+ (UIImage *)imageGradientWithStartColor:(UIColor *)startColor endColor:(UIColor *)endColor size:(CGSize)size {
// Allocate color space.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Allocate bitmap context.
CGContextRef bitmapCotext = CGBitmapContextCreate(NULL, size.width, size.height, 8, 4 * size.width, colorSpace, kCGImageAlphaPremultipliedFirst);
// Create the gradient.
CGFloat locations[2] = { 0.0f, 1.0f };
COLOR_RGBA startRgba = [LMFunctions rgbaFromUIColor:startColor];
COLOR_RGBA endRgba = [LMFunctions rgbaFromUIColor:endColor];
CGFloat components[8] = {
startRgba.r, startRgba.g, startRgba.b, 1.0f, // Start color.
endRgba.r, endRgba.g, endRgba.b, 1.0f }; // End color.
CGGradientRef myGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 2);
// Draw gradient here.
CGContextDrawLinearGradient(bitmapCotext, myGradient, CGPointMake(0, 0), CGPointMake(size.width, size.height), kCGGradientDrawsAfterEndLocation);
// Create a CGImage from context.
CGImageRef cgImage = CGBitmapContextCreateImage(bitmapCotext);
// Create a UIImage from CGImage.
UIImage *uiImage = [UIImage imageWithCGImage:cgImage];
// Release resources.
CGGradientRelease(myGradient);
CGImageRelease(cgImage);
CGContextRelease(bitmapCotext);
CGColorSpaceRelease(colorSpace);
return uiImage;
}
Download the ready-for-use source file (.m) of UIImage gradient from two Colors
No comments:
Post a Comment