How can I create a UIColor from a hex string?

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

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

相关标签:
30条回答
  • 2020-11-22 17:21

    Create elegant extension for UIColor:

    extension UIColor {
    
    convenience init(string: String) {
    
            var uppercasedString = string.uppercased()
            uppercasedString.remove(at: string.startIndex)
    
            var rgbValue: UInt32 = 0
            Scanner(string: uppercasedString).scanHexInt32(&rgbValue)
    
            let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
            let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
            let blue = CGFloat(rgbValue & 0x0000FF) / 255.0
    
            self.init(red: red, green: green, blue: blue, alpha: 1)
        }
    }
    

    Create red color:

    let red = UIColor(string: "#ff0000") 
    
    0 讨论(0)
  • 2020-11-22 17:24

    I created a convenience init for that:

    extension UIColor {
    convenience init(hex: String, alpha: CGFloat)
    {
        let redH = CGFloat(strtoul(hex.substringToIndex(advance(hex.startIndex,2)), nil, 16))
        let greenH = CGFloat(strtoul(hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 2), end: advance(hex.startIndex, 4))), nil, 16))
        let blueH = CGFloat(strtoul(hex.substringFromIndex(advance(hex.startIndex,4)), nil, 16))
    
        self.init(red: redH/255, green: greenH/255, blue: blueH/255, alpha: alpha)
    }
    }
    

    then you can create an UIColor anywhere in your project just like this:

    UIColor(hex: "ffe3c8", alpha: 1)
    

    hope this helps...

    0 讨论(0)
  • 2020-11-22 17:24

    You can create extension class of UIColor as:-

    extension UIColor {

    // MARK: - getColorFromHex /** This function will convert the color Hex code to RGB.

    - parameter color  hex string.
    
    - returns: RGB color code.
    */
    class func getColorFromHex(hexString:String)->UIColor{
    
        var rgbValue : UInt32 = 0
        let scanner:NSScanner =  NSScanner(string: hexString)
    
        scanner.scanLocation = 1
        scanner.scanHexInt(&rgbValue)
    
        return UIColor(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0))
    }
    

    }

    0 讨论(0)
  • 2020-11-22 17:25

    updated for swift 1.2

    class func colorWithHexString (hex:String) -> UIColor {
        var cString: NSString = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
    
        if (cString.hasPrefix("#")) {
            cString = cString.substringFromIndex(1)
        }
    
        if (count(cString as String) != 6) {
            return UIColor.grayColor()
        }
    
        var rString: String = cString.substringToIndex(2)
        var gString: String = (cString.substringFromIndex(2) as NSString).substringToIndex(2)
        var bString: String = (cString.substringFromIndex(4) as NSString).substringToIndex(2)
    
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        NSScanner(string: rString).scanHexInt(&r)
        NSScanner(string: gString).scanHexInt(&g)
        NSScanner(string: bString).scanHexInt(&b)
        return UIColor(red: CGFloat(Float(r) / 255.0), green: CGFloat(Float(g) / 255.0), blue: CGFloat(Float(b) / 255.0), alpha: CGFloat(1))
    
    }
    
    0 讨论(0)
  • 2020-11-22 17:28

    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 
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题