How can I create a UIColor from a hex string? How can I create a UIColor from a hex string? ios ios

How can I create a UIColor from a hex string?


I've found the simplest way to do this is with a macro. Just include it in your header and it's available throughout your project.

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

uicolor macro with hex values

Also formatted version of this code:

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

Usage:

label.textColor = UIColorFromRGB(0xBC1128);

Swift:

static func UIColorFromRGB(_ rgbValue: Int) -> UIColor! {    return UIColor(        red: CGFloat((Float((rgbValue & 0xff0000) >> 16)) / 255.0),        green: CGFloat((Float((rgbValue & 0x00ff00) >> 8)) / 255.0),        blue: CGFloat((Float((rgbValue & 0x0000ff) >> 0)) / 255.0),        alpha: 1.0)}


A concise solution:

// Assumes input like "#00FF00" (#RRGGBB).+ (UIColor *)colorFromHexString:(NSString *)hexString {    unsigned rgbValue = 0;    NSScanner *scanner = [NSScanner scannerWithString:hexString];    [scanner setScanLocation:1]; // bypass '#' character    [scanner scanHexInt:&rgbValue];    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];}


I've got a solution that is 100% compatible with the hex format strings used by Android, which I found very helpful when doing cross-platform mobile development. It lets me use one color palate for both platforms. Feel free to reuse without attribution, or under the Apache license if you prefer.

#import "UIColor+HexString.h"@interface UIColor(HexString)+ (UIColor *) colorWithHexString: (NSString *) hexString;+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length;@end@implementation UIColor(HexString)+ (UIColor *) colorWithHexString: (NSString *) hexString {    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];    CGFloat alpha, red, blue, green;    switch ([colorString length]) {        case 3: // #RGB            alpha = 1.0f;            red   = [self colorComponentFrom: colorString start: 0 length: 1];            green = [self colorComponentFrom: colorString start: 1 length: 1];            blue  = [self colorComponentFrom: colorString start: 2 length: 1];            break;        case 4: // #ARGB            alpha = [self colorComponentFrom: colorString start: 0 length: 1];            red   = [self colorComponentFrom: colorString start: 1 length: 1];            green = [self colorComponentFrom: colorString start: 2 length: 1];            blue  = [self colorComponentFrom: colorString start: 3 length: 1];                      break;        case 6: // #RRGGBB            alpha = 1.0f;            red   = [self colorComponentFrom: colorString start: 0 length: 2];            green = [self colorComponentFrom: colorString start: 2 length: 2];            blue  = [self colorComponentFrom: colorString start: 4 length: 2];                                  break;        case 8: // #AARRGGBB            alpha = [self colorComponentFrom: colorString start: 0 length: 2];            red   = [self colorComponentFrom: colorString start: 2 length: 2];            green = [self colorComponentFrom: colorString start: 4 length: 2];            blue  = [self colorComponentFrom: colorString start: 6 length: 2];                                  break;        default:            [NSException raise:@"Invalid color value" format: @"Color value %@ is invalid.  It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString];            break;    }    return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];}+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {    NSString *substring = [string substringWithRange: NSMakeRange(start, length)];    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];    unsigned hexComponent;    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];    return hexComponent / 255.0;}@end 

Swift:

extension UIColor {    convenience init?(hexString: String?) {        let input: String! = (hexString ?? "")            .replacingOccurrences(of: "#", with: "")            .uppercased()        var alpha: CGFloat = 1.0        var red: CGFloat = 0        var blue: CGFloat = 0        var green: CGFloat = 0        switch (input.count) {        case 3 /* #RGB */:            red = Self.colorComponent(from: input, start: 0, length: 1)            green = Self.colorComponent(from: input, start: 1, length: 1)            blue = Self.colorComponent(from: input, start: 2, length: 1)            break        case 4 /* #ARGB */:            alpha = Self.colorComponent(from: input, start: 0, length: 1)            red = Self.colorComponent(from: input, start: 1, length: 1)            green = Self.colorComponent(from: input, start: 2, length: 1)            blue = Self.colorComponent(from: input, start: 3, length: 1)            break        case 6 /* #RRGGBB */:            red = Self.colorComponent(from: input, start: 0, length: 2)            green = Self.colorComponent(from: input, start: 2, length: 2)            blue = Self.colorComponent(from: input, start: 4, length: 2)            break        case 8 /* #AARRGGBB */:            alpha = Self.colorComponent(from: input, start: 0, length: 2)            red = Self.colorComponent(from: input, start: 2, length: 2)            green = Self.colorComponent(from: input, start: 4, length: 2)            blue = Self.colorComponent(from: input, start: 6, length: 2)            break        default:            NSException.raise(NSExceptionName("Invalid color value"), format: "Color value \"%@\" is invalid.  It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", arguments:getVaList([hexString ?? ""]))        }        self.init(red: red, green: green, blue: blue, alpha: alpha)    }        static func colorComponent(from string: String!, start: Int, length: Int) -> CGFloat {        let substring = (string as NSString)            .substring(with: NSRange(location: start, length: length))        let fullHex = length == 2 ? substring : "\(substring)\(substring)"        var hexComponent: UInt64 = 0        Scanner(string: fullHex)            .scanHexInt64(&hexComponent)        return CGFloat(Double(hexComponent) / 255.0)    }}