How can I create a UIColor from a hex string?

后端 未结 30 1680
北恋
北恋 2020-11-22 16:53

How can I create a UIColor from a hexadecimal string format, such as #00FF00?

30条回答
  •  再見小時候
    2020-11-22 17:30

    I found a good UIColor category for this, UIColor+PXExtensions.

    Usage: UIColor *mycolor = [UIColor pxColorWithHexValue:@"#BADA55"];

    And, just in case the link to my gist fails, here is the actual implementation code:

    //
    //  UIColor+PXExtensions.m
    //
    
    #import "UIColor+UIColor_PXExtensions.h"
    
    @implementation UIColor (UIColor_PXExtensions)
    
    + (UIColor*)pxColorWithHexValue:(NSString*)hexValue
    {
        //Default
        UIColor *defaultResult = [UIColor blackColor];
    
        //Strip prefixed # hash
        if ([hexValue hasPrefix:@"#"] && [hexValue length] > 1) {
            hexValue = [hexValue substringFromIndex:1];
        }
    
        //Determine if 3 or 6 digits
        NSUInteger componentLength = 0;
        if ([hexValue length] == 3)
        {
            componentLength = 1;
        }
        else if ([hexValue length] == 6)
        {
            componentLength = 2;
        }
        else
        {
            return defaultResult;
        }
    
        BOOL isValid = YES;
        CGFloat components[3];
    
        //Seperate the R,G,B values
        for (NSUInteger i = 0; i < 3; i++) {
            NSString *component = [hexValue substringWithRange:NSMakeRange(componentLength * i, componentLength)];
            if (componentLength == 1) {
                component = [component stringByAppendingString:component];
            }
            NSScanner *scanner = [NSScanner scannerWithString:component];
            unsigned int value;
            isValid &= [scanner scanHexInt:&value];
            components[i] = (CGFloat)value / 256.0f;
        }
    
        if (!isValid) {
            return defaultResult;
        }
    
        return [UIColor colorWithRed:components[0]
                               green:components[1]
                                blue:components[2]
                               alpha:1.0];
    }
    
    @end
    

提交回复
热议问题