Created by Jamz Tang at 22 August 2011

Creating a placeholder UIImage dynamically with color

Ever needed a placeholder color for your lazy loaded table view cell image view? Typically can create a 1x1 pixel image in PhotoShop, add it to your project, then load it with UIImageNamed. Can't imagine how lots of effort and steps, and if the placeholder color are requested to be updated, you'd have to repeat the process all over again.

If you needed work with this kind of situations a lot, lets do it programmatically and DRY! Consider the following UIImage-JTColor category.

/*
 * This file is part of the http://ioscodesnippet.com
 * (c) Jamz Tang <jamz@jamztang.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import <UIKit/UIKit.h>

@interface UIImage (JTColor)

+ (UIImage *)imageWithColor:(UIColor *)color;

@end
/*
 * This file is part of the http://ioscodesnippet.com
 * (c) Jamz Tang <jamz@jamztang.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "UIImage-JTColor.h"

@implementation UIImage (JTColor)

+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    // Create a 1 by 1 pixel context
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    [color setFill];
    UIRectFill(rect);   // Fill it with your color
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

@end

Usage:

#import "UIImage-JTColor.h"

UIColor *color = [UIColor lightGrayColor];   // Or your whatever UIColor
imageView.image = [UIImage imageWithColor:color];

Nothing magical but will saves you a lot of time.


Installation

Using CocoaPods: [?]
pod 'UIImage-JTColor', '~> 0.0.1'

Clone this repository:
git clone git://gist.github.com/1571875.git UIImage-JTColor

Download | More...


If you think this is useful, share this article with your friends :)

blog comments powered by Disqus

ioscodesnippet.com