skip to Main Content
+971 55 881 1725 hmimthiaz @ imthi.com

iPhone SDK convert hex color string to UIColor

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

Class.h

Class.m

This Post Has 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.

Back To Top