Skip to content

Instantly share code, notes, and snippets.

@hartbit
Created April 10, 2011 13:08
Show Gist options
  • Save hartbit/912327 to your computer and use it in GitHub Desktop.
Save hartbit/912327 to your computer and use it in GitHub Desktop.
UIImage Category for loading images correctly.
#import "UIImage+Loading.h"
#import "HDFoundation.h"
#import "UIDevice+Platform.h"
@interface UIImage ()
+ (UIImage*)findImageNamed:(NSString*)name cached:(BOOL)caches;
@end
@implementation UIImage (HDLoading)
#pragma - Public Methods
+ (NSArray*)supportedTypes
{
static NSArray* kSupportedTypes = nil;
if (!kSupportedTypes)
{
kSupportedTypes = [[NSArray alloc] initWithObjects:
@"png",
@"jpg", @"jpeg",
@"tiff", @"tif",
@"gif",
@"bmp", @"BMPf",
@"ico",
@"cur",
@"xbm", nil];
}
return kSupportedTypes;
}
+ (UIImage*)imageNamed:(NSString*)name cached:(BOOL)cached
{
HDCheck(isObjectNotNil(name), HDFailureLevelWarning, return nil);
NSString* platformSuffix = [[UIDevice currentDevice] platformSuffix];
NSString* platformName = [name stringByAppendingString:platformSuffix];
UIImage* image = nil;
image = [UIImage findImageNamed:platformName cached:cached];
if (image) return image;
image = [UIImage findImageNamed:name cached:cached];
if (image) return image;
return [UIImage imageNamed:name];
}
#pragma - Private Methods
+ (UIImage*)findImageNamed:(NSString*)name cached:(BOOL)cached
{
NSBundle* mainBundle = [NSBundle mainBundle];
for (NSString* type in [UIImage supportedTypes])
{
NSString* path = [mainBundle pathForResource:name ofType:type];
NSLog(@"pathForResource");
if (path)
{
if (cached)
{
NSString* fullName = [name stringByAppendingFormat:@".%@", type];
return [UIImage imageNamed:fullName];
}
else
{
return [UIImage imageWithContentsOfFile:path];
}
}
}
return nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment