How to convert HEX RGB color codes to UIColor?

IphoneUicolor

Iphone Problem Overview


I have an RGB hex code like #ffffff as NSString and want to convert that into an UIColor. Is there a simple way to do that?

Iphone Solutions


Solution 1 - Iphone

In some code of mine, I use 2 different functions:

void SKScanHexColor(NSString * hexString, float * red, float * green, float * blue, float * alpha) {
  NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
  if([cleanString length] == 3) {
      cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@", 
                     [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                     [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                     [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
  }
  if([cleanString length] == 6) {
      cleanString = [cleanString stringByAppendingString:@"ff"];
  }

  unsigned int baseValue;
  [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];

  if (red) { *red = ((baseValue >> 24) & 0xFF)/255.0f; }
  if (green) { *green = ((baseValue >> 16) & 0xFF)/255.0f; }
  if (blue) { *blue = ((baseValue >> 8) & 0xFF)/255.0f; }
  if (alpha) { *alpha = ((baseValue >> 0) & 0xFF)/255.0f; }
}

And then I use it like this:

UIColor * SKColorFromHexString(NSString * hexString) {
  float red, green, blue, alpha;
  SKScanHexColor(hexString, &red, &green, &blue, &alpha);

  return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

If you prefer to use this as a UIColor category, then it's just a matter of altering a few lines:

+ (UIColor *) colorFromHexString:(NSString *)hexString {
  NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
  if([cleanString length] == 3) {
      cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@", 
                     [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                     [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                     [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
  }
  if([cleanString length] == 6) {
      cleanString = [cleanString stringByAppendingString:@"ff"];
  }

  unsigned int baseValue;
  [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];

  float red = ((baseValue >> 24) & 0xFF)/255.0f;
  float green = ((baseValue >> 16) & 0xFF)/255.0f;
  float blue = ((baseValue >> 8) & 0xFF)/255.0f;
  float alpha = ((baseValue >> 0) & 0xFF)/255.0f;
  
  return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

This will handle strings like "#abc", "#abcdef31", etc.

Solution 2 - Iphone

If you are using Hex Values..

#define UIColorFromRGB(rgbValue) [UIColor \
       colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
       green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
       blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

  //Then use any Hex value
    
 self.view.backgroundColor = UIColorFromRGB(0xD2691E);   

Solution 3 - Iphone

I was looking for a simple solution and came up with this (not completely Objective-C, but works like a charm):

NSString *stringColor = @"#AABBCC";
NSUInteger red, green, blue;
sscanf([stringColor UTF8String], "#%02X%02X%02X", &red, &green, &blue);

UIColor *color = [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];

Solution 4 - Iphone

There is a nice category for UIColor called "UIColor+Expanded" which has a class method for getting a UIColor from an RGB hex string:

It's simple to use:

UIColor *myColor = [UIColor colorWithHexString:@"FF0000"];

Plus it adds a lot of other potentially useful utilities to UIColor. More info is available in this article.

Solution 5 - Iphone

Easy, Just go to this website and type in your hex value: http://www.corecoding.com/utilities/rgb-or-hex-to-float.php

Solution 6 - Iphone

+ (UIColor *)colorWithHexString:(NSString *)colorString
{
    colorString = [colorString stringByReplacingOccurrencesOfString:@"#" withString:@""];

    if (colorString.length == 3)
        colorString = [NSString stringWithFormat:@"%c%c%c%c%c%c",
        [colorString characterAtIndex:0], [colorString characterAtIndex:0],
        [colorString characterAtIndex:1], [colorString characterAtIndex:1],
        [colorString characterAtIndex:2], [colorString characterAtIndex:2]];

    if (colorString.length == 6)
    {
        int r, g, b;
        sscanf([colorString UTF8String], "%2x%2x%2x", &r, &g, &b);
        return [UIColor colorWithRed:(r/255.0) green:(g/255.0) blue:(b/255.0) alpha:1.0];
    }
    return nil;
}

for format #123, 123, #fff195, fff195

+ (UIColor *)colorWithHexValue:(int)hexValue
{
    float red   = ((hexValue & 0xFF0000) >> 16)/255.0;
    float green = ((hexValue & 0xFF00) >> 8)/255.0;
    float blue  = (hexValue & 0xFF)/255.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

for format 0xfff195

Solution 7 - Iphone

The easiest way that I found: Hex to UIColor Converter

Just type the hex number without '#', and it returns the UIColor code. For example the code for the orange color (#f77f00) is:

[UIColor colorWithRed:0.969 green:0.498 blue:0 alpha:1.0]

Solution 8 - Iphone

I think I'd split the six characters into three pairs, then convert that to decimal, then divide that by 255 to get each color component as a float.

You can then pass the components to:

[UIColor colorWithRed: green: blue: alpha:1];

Solution 9 - Iphone

I created an online tool to instantly convert any hex code to a UIColor code snippet for Swift and Objective-C, for when it's inconvenient to use custom methods or plugins: https://iosref.com/uihex/

Solution 10 - Iphone

If converting from ObjectiveC to swift is hard for you, here's the answer with Swift. Currently it only takes strings without the #, but you can add a scanner method to skip it I believe.

func stringToColor(stringColor: String) -> UIColor {
    var hexInt: UInt32 = 0
    let scanner = NSScanner(string: stringColor)
    scanner.scanHexInt(&hexInt)
    let color = UIColor(
        red: CGFloat((hexInt & 0xFF0000) >> 16)/255,
        green: CGFloat((hexInt & 0xFF00) >> 8)/255,
        blue: CGFloat((hexInt & 0xFF))/255,
        alpha: 1)
    
    return color
}

Solution 11 - Iphone

If you don't want to write all of this code above, you can check this site: http://www.diovo.com/apps/rgb-to-uicolor-converter.html
From an HEX color like this: #FFFFFF, the site convert it in a string like this:

UIColor *aColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1.000];

Solution 12 - Iphone

Don't forget that you have the option to convert your hex values to RGB and enter them in the interface builder. It'll save some lines of code.

rgb sliders

Solution 13 - Iphone

Guess this is a bit late here... but I found this version in the WhiteHouse Github repo that does it in a pretty elegant way:

+(UIColor *)colorFromRGBHexString:(NSString *)colorString {
    if(colorString.length == 7) {
        const char *colorUTF8String = [colorString UTF8String];
        int r, g, b;
        sscanf(colorUTF8String, "#%2x%2x%2x", &r, &g, &b);
        return [UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:1.0];
    }    
    return nil;
}

[Source Link to their WHAppConfig.m on github][1]

[1]: https://github.com/WhiteHouse/wh-app-ios/blob/1ae426b03816c5fb45cc23fe62d435aadfc03afa/WhiteHouseApp/WHAppConfig.m#L97-L106 "WHAppConfig.m"

Solution 14 - Iphone

I think there is an even easier way when using HEX values. Just add a definition at the top of your file or reference a header file for the conversion (UIColorFromRGB). You can even add a template of fixed HEX color values.

#define CLR_YELLOW_TEXT     0xf4dc89    // A Light Yellow text
#define CLR_GREEN_TEXT      0x008040	// Dark Green text for my buttons

#define UIColorFromRGB(rgbValue)  [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

Then just reference it in your code using the HEX values directly or your defined hex values. For example...

[myButton1 setTitleColor:UIColorFromRGB(0xd02d2d) forState:UIControlStateNormal];
[myButton2 setTitleColor:UIColorFromRGB(CLR_GREEN_TEXT) forState:UIControlStateNormal];
[myButton3 setTitleColor:UIColorFromRGB(CLR_YELLOW_TEXT) forState:UIControlStateNormal];

(PS - This assumes an Alpha of 1.0, but it can always be changed in the definition).

Enjoy.

Solution 15 - Iphone

I found a cocoapod library very useful in creating UIColor using "#RRGGBB" values.

pod 'UIColor-HexRGB'

Solution 16 - Iphone

+(UIColor*)colorWithHexString:(NSString*)hexString

{

NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

if ([cString length] < 6) return [UIColor grayColor];

if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];

if ([cString length] != 6) return  [UIColor grayColor];

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];

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];

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionopenfrogView Question on Stackoverflow
Solution 1 - IphoneDave DeLongView Answer on Stackoverflow
Solution 2 - Iphonek-thoratView Answer on Stackoverflow
Solution 3 - IphoneBhatiaView Answer on Stackoverflow
Solution 4 - IphoneJim RhoadesView Answer on Stackoverflow
Solution 5 - IphoneMikeTheCoderView Answer on Stackoverflow
Solution 6 - IphoneChikabuZView Answer on Stackoverflow
Solution 7 - IphoneEhsanView Answer on Stackoverflow
Solution 8 - IphoneCodebeefView Answer on Stackoverflow
Solution 9 - IphoneEugeneView Answer on Stackoverflow
Solution 10 - IphoneTom PratsView Answer on Stackoverflow
Solution 11 - IphonematteodvView Answer on Stackoverflow
Solution 12 - IphoneKyle CleggView Answer on Stackoverflow
Solution 13 - IphoneJonathon HibbardView Answer on Stackoverflow
Solution 14 - IphoneBlaine LView Answer on Stackoverflow
Solution 15 - IphoneRameshView Answer on Stackoverflow
Solution 16 - IphoneKemoView Answer on Stackoverflow