iPhone SDK convert hex color string to UIColor

This function will help you to convert hex color string to UIColor

Class.h

+ (UIColor *) colorWithHexString: (NSString *) stringToConvert;

Class.m

+ (UIColor *) colorWithHexString: (NSString *) stringToConvert{
	NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
	// String should be 6 or 8 characters
	if ([cString length] < 6) return [UIColor blackColor];
	// strip 0X if it appears
	if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
	if ([cString length] != 6) return [UIColor blackColor];
	// Separate into r, g, b substrings
	NSRange range;
	range.location = 0;
	range.length = 2;
	NSString *rString = [cString substringWithRange:range];
	range.location = 2;
	NSString *gString = [cString substringWithRange:range];
	range.location = 4;
	NSString *bString = [cString substringWithRange:range];
	// Scan values
	unsigned int r, g, b;
	[[NSScanner scannerWithString:rString] scanHexInt:&r];
	[[NSScanner scannerWithString:gString] scanHexInt:&g];
	[[NSScanner scannerWithString:bString] scanHexInt:&b];
	
	return [UIColor colorWithRed:((float) r / 255.0f)
						   green:((float) g / 255.0f)
							blue:((float) b / 255.0f)
						   alpha:1.0f];
}

By Imthiaz

Programmer, SAAS, CMS & CRM framework designer, Love Linux & Apple products, Currently addicted to mobile development & working @bluebeetle

4 comments

  1. Here’s something along those lines, but more concise:

    #define TEST_COLOR @”#f73e0a”
    unsigned int c;
    if ([TEST_COLOR characterAtIndex:0] == ‘#’) {
    [[NSScanner scannerWithString:[TEST_COLOR substringFromIndex:1]] scanHexInt:&c];
    } else {
    [[NSScanner scannerWithString:TEST_COLOR] scanHexInt:&c];
    }
    img.backgroundColor = [UIColor colorWithRed:((c & 0xff0000) >> 16)/255 green:((c & 0xff00) >> 8)/255 blue:(c & 0xff)/255 alpha:1.0];

  2. Sorry. I should have just copied our category in (which anyone can rename to whatever they want, of course):

    #import

    @interface NSString (meltutils)
    – (UIColor *)toUIColor;
    @end

    @implementation NSString (meltutils)
    – (UIColor *)toUIColor {
    unsigned int c;
    if ([self characterAtIndex:0] == ‘#’) {
    [[NSScanner scannerWithString:[self substringFromIndex:1]] scanHexInt:&c];
    } else {
    [[NSScanner scannerWithString:self] scanHexInt:&c];
    }
    return [UIColor colorWithRed:((c & 0xff0000) >> 16)/255.0 green:((c & 0xff00) >> 8)/255.0 blue:(c & 0xff)/255.0 alpha:1.0];
    }
    @end

    Then just use like this (I have the above interface and implementation stored in NSString+meltutils.h and NSString+meltutils.m):

    #import “NSString+meltutils.h”

    UIColor *aColorStr = [@”#f82a01″ toUIColor];

    Maybe that will help someone out. 🙂

Comments are closed.