我如何从十六进制字符串格式创建一个UIColor,如#00FF00?


当前回答

除了颜色,我还喜欢保证alpha,所以我自己写类别

+ (UIColor *) colorWithHex:(int)color {

    float red = (color & 0xff000000) >> 24;
    float green = (color & 0x00ff0000) >> 16;
    float blue = (color & 0x0000ff00) >> 8;
    float alpha = (color & 0x000000ff);

    return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha/255.0];
}

像这样很容易使用

[UIColor colorWithHex:0xFF0000FF]; //Red
[UIColor colorWithHex:0x00FF00FF]; //Green
[UIColor colorWithHex:0x00FF00FF]; //Blue
[UIColor colorWithHex:0x0000007F]; //transparent black

其他回答

为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)
    }
}

创建红色:

let red = UIColor(string: "#ff0000") 

斯威夫特版本:

extension UIColor {
    convenience init?(var hex: String) {
        hex = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
        hex = (hex.hasPrefix("#")) ? hex.substringFromIndex(advance(hex.startIndex, 1)) : hex

        var value: UInt32 = 0
        if NSScanner(string: hex).scanHexInt(&value) {
            if count(hex) == 8 {
                self.init(red: CGFloat((value & 0xFF000000) >> 24) / 255.0,
                    green: CGFloat((value & 0x00FF0000) >> 16) / 255.0,
                    blue: CGFloat((value & 0x0000FF00) >> 8) / 255.0,
                    alpha: CGFloat((value & 0x000000FF)) / 255.0)
                return
            } else if count(hex) == 6 {
                self.init(red: CGFloat((value & 0xFF0000) >> 16) / 255.0,
                    green: CGFloat((value & 0x00FF00) >> 8) / 255.0,
                    blue: CGFloat(value & 0x0000FF) / 255.0,
                    alpha: 1.0)
                return
            }
        }
        self.init()
        return nil
    }
}

抛光扩展从原来的答案@Tom 请随意在这里更新代码

extension UIColor{
    convenience init (hexString:String) {
        var cleanString:String = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString

        if (cleanString.hasPrefix("#")) {
            cleanString = cleanString.substringFromIndex(cleanString.startIndex.advancedBy(1))
        }

        if (cleanString.characters.count != 6) {
            self.init()
        }
        else{
            var rgbValue = UInt32()
            let scanner = NSScanner(string: cleanString)
            scanner.scanHexInt(&rgbValue)

            self.init(
                red: CGFloat((rgbValue & 0xFF0000) >> 16)/255.0,
                green: CGFloat((rgbValue & 0xFF00) >> 8)/255.0,
                blue: CGFloat(rgbValue & 0xFF)/255.0,
                alpha: 1.0)
        }
    }
}

我找到了一个很好的UIColor类别,UIColor+PXExtensions。

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

而且,为了防止链接到我的要点失败,这里是实际的实现代码:

//
//  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

伊森·斯特里德回答的简单例子。一个接受十六进制字符串并返回UIColor的函数。 (你可以输入十六进制字符串格式:#ffffff或ffffff)

例子:

func hexStringToUIColor (hex:String) -> UIColor {
    var cString: String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        if let range = cString.range(of: cString) {
            cString = cString.substring(from: cString.index(range.lowerBound, offsetBy: 1))
        }
    }

    if ((cString.characters.count) != 6) {
        return UIColor.gray
    }

    var rgbValue: UInt32 = 0
    Scanner(string: cString).scanHexInt32(&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)
    )
}

用法:

var color1 = hexStringToUIColor("#d3d3d3")