Skip to content

Instantly share code, notes, and snippets.

@jamztang
Created January 6, 2012 18:48
Show Gist options
  • Select an option

  • Save jamztang/1571875 to your computer and use it in GitHub Desktop.

Select an option

Save jamztang/1571875 to your computer and use it in GitHub Desktop.
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.

<script src="https://gist.github.com/1571875.js?file=UIImage%2BJTColor.h"> </script> <script src="https://gist.github.com/1571875.js?file=UIImage%2BJTColor.m"> </script>

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.

//
// UIImage+JTColor.h
//
// Created by james on 8/22/11.
//
#import <UIKit/UIKit.h>
@interface UIImage (JTColor)
+ (UIImage *)imageWithColor:(UIColor *)color;
@end
//
// UIImage+JTColor.m
//
// Created by james on 8/22/11.
//
#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
@klauslanza
Copy link

Loving it, hope it stays here so I can use it in my podfiles!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment