65

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?

openfrog
  • 40,201
  • 65
  • 225
  • 373
  • If you don't want to do this with code you can have a look at [http://uicolor.io/](http://uicolor.io/). Converts easily HEX & RGB to UIColor for both Swift & Objective-C plus there is a color picker just in case... – manosim Dec 26 '14 at 20:27
  • 3
    Just an update - the url of `http://uicolor.io/` has changed [http://uicolor.xyz](http://uicolor.xyz) – manosim Jan 09 '16 at 12:11

16 Answers16

101

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.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • 2
    I understand everything up to: `((baseValue >> 24) & 0xFF)`. (I get the division by 255.0f). Could you explain how you arrive at shifting 24, 16, and 8 bits? And also, why are you &'ing with 0xFF? Thank you :) – Matt H. Nov 30 '12 at 06:19
  • Maybe the correct answer, but is some kind of "funny" heard this: "Is there a simple way to do that?" and we need to write a book to do it. – Sulfkain Nov 19 '14 at 15:30
  • First link in answer is dead (stackkit.com). – Pang Aug 09 '15 at 06:18
84

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);   
k-thorat
  • 4,873
  • 1
  • 27
  • 36
35

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];
Bhatia
  • 351
  • 3
  • 2
19

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.

Jim Rhoades
  • 3,310
  • 3
  • 34
  • 50
  • It doesn't show any problems but it doesn't work, I imported UIColor+Expanded.h and UIColor+Expanded.m. Heres the line. self.navigationController.navigationBar.tintColor = [UIColor colorWithHexString:@"#555555"]; – Souljacker Sep 03 '11 at 19:29
  • 1
    @Ravin455 You probably need to take out that # symbol (as shown in my original answer). – Jim Rhoades Sep 07 '11 at 11:38
  • 1
    The link for the category is broken. – Ricardo Sanchez-Saez Apr 09 '13 at 10:29
  • Try colorWithHexString and colorWithName from: https://github.com/phonegap/phonegap-plugins/blob/master/iPhone/NotificationEx/UIColor-Expanded.m – Mark Phillip Sep 01 '13 at 19:01
  • I updated the original post to point to the new location of UIColor+Expanded, which is here: https://github.com/erica/uicolor-utilities/tree/master/Color – Jim Rhoades Jan 30 '14 at 17:00
10

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

MikeTheCoder
  • 963
  • 3
  • 12
  • 24
7
+ (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

ChikabuZ
  • 10,031
  • 5
  • 63
  • 86
5

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]
Ehsan
  • 1,022
  • 11
  • 20
3

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/

Eugene
  • 3,417
  • 5
  • 25
  • 49
3

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
}
App Dev Guy
  • 5,396
  • 4
  • 31
  • 54
Tom Prats
  • 7,364
  • 9
  • 47
  • 77
3

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];
Codebeef
  • 43,508
  • 23
  • 86
  • 119
2

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];
matteodv
  • 3,992
  • 5
  • 39
  • 73
1

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

Kyle Clegg
  • 38,547
  • 26
  • 130
  • 141
1

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

Jonathon Hibbard
  • 1,547
  • 13
  • 20
0

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.

0

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

pod 'UIColor-HexRGB'
Ramesh
  • 1,703
  • 18
  • 13
0
+(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];

}

Community
  • 1
  • 1
Kemo
  • 488
  • 6
  • 12