o9s
is a microblog
home archives search feed blogroll


Colors With HEX Strings

This function proves useful again and again in my projects. As the name suggests, it converts a HEX string to a UIColor.

As an example, it would convert #FFFFFF to [UIColor whiteColor].

+ (UIColor*)colorWithHexString:(NSString*)hexString {
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""] uppercaseString];
    CGFloat alpha, red, blue, green;

    switch ([colorString length]) {
        case 3: // #RGB
            red = [self colorComponentFrom:colorString start:0 length:1];
            green = [self colorComponentFrom:colorString start:1 length:1];
            blue = [self colorComponentFrom:colorString start:2 length:1];
            alpha = 1.0f;
            break;
        case 4: // #RGBA
            red = [self colorComponentFrom:colorString start:0 length:1];
            green = [self colorComponentFrom:colorString start:1 length:1];
            blue = [self colorComponentFrom:colorString start:2 length:1];
            alpha = [self colorComponentFrom:colorString start:3 length:1];
            break;
        case 6: // #RRGGBB
            red = [self colorComponentFrom:colorString start:0 length:2];
            green = [self colorComponentFrom:colorString start:2 length:2];
            blue = [self colorComponentFrom:colorString start:4 length:2];
            alpha = 1.0f;
            break;
        case 8: // #RRGGBBAA
            red = [self colorComponentFrom:colorString start:0 length:2];
            green = [self colorComponentFrom:colorString start:2 length:2];
            blue = [self colorComponentFrom:colorString start:4 length:2];
            alpha = [self colorComponentFrom:colorString start:6 length:2];
            break;
        default:
            return nil;
    }

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

I always use HEX strings for colors on Android. When porting Android apps to iOS, I would have to convert HEX strings to RGB and use [UIColor colorWithRed:green:blue:alpha]. Not anymore. This bit of code helps me save some time.

I usually put this code in a class called ColorUtils.

Isn’t it a bit surprising that iOS does not handle web colors?

Posted on 2018-03-30   #ios     #objc  






← Next post    ·    Previous post →