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


当前回答

extension UIColor {
    convenience init(hexaString: String, alpha: CGFloat = 1) {
        let chars = Array(hexaString.dropFirst())
        self.init(red:   .init(strtoul(String(chars[0...1]),nil,16))/255,
                  green: .init(strtoul(String(chars[2...3]),nil,16))/255,
                  blue:  .init(strtoul(String(chars[4...5]),nil,16))/255,
                  alpha: alpha)}
}

用法:

let redColor       = UIColor(hexaString: "#FF0000")              // r 1,0 g 0,0 b 0,0 a 1,0
let transparentRed = UIColor(hexaString: "#FF0000", alpha: 0.5)  // r 1,0 g 0,0 b 0,0 a 0,5


另一种选择是将六值转换为无符号整数,并从中提取相应的值:

extension UIColor {
    convenience init(hexaString: String, alpha: CGFloat = 1) {
        self.init(hexa: UInt(hexaString.dropFirst(), radix: 16) ?? 0, alpha: alpha)
    }
    convenience init(hexa: UInt, alpha: CGFloat = 1) {
        self.init(red:   .init((hexa & 0xff0000) >> 16) / 255,
                  green: .init((hexa & 0xff00  ) >>  8) / 255,
                  blue:  .init( hexa & 0xff    )        / 255,
                  alpha: alpha)
    }
}

let purpleColor       = UIColor(hexaString: "#FF00FF")    // r 1,0 g 0,0 b 1,0 a 1,0
let transparentYellow = UIColor(hexaString: "#FFFF00", alpha: 0.5)  // r 1,0 g 1,0 b 0,0 a 0,5

其他回答

你可以创建UIColor的扩展类:-

扩展UIColor {

// MARK: - getColorFromHex /** 此函数将颜色十六进制代码转换为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))
}

}

上面的几个解决方案涉及到一些不必要的nsstring使用。这个UIColor类扩展更简单更快:

+ colorWithHex:(UInt32)hex alpha:(CGFloat)alpha
{
    return [UIColor colorWithRed:((hex & 0xFF0000) >> 16)/255.0
                           green:((hex & 0x00FF00) >> 8)/255.0
                            blue:( hex & 0x0000FF)/255.0
                           alpha:alpha];
}

简单来说:

return [UIColor colorWithHex:0x006400 alpha:1.0]; // HTML darkgreen

Swift 5, iOS 14

convenience init(hex: String, alpha: CGFloat = 1.0) {
    var hexFormatted: String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
    
    if hexFormatted.hasPrefix("#") {
        hexFormatted = String(hexFormatted.dropFirst())
    }
    
    assert(hexFormatted.count == 6, "Invalid hex code used.")
    
    var rgbValue: UInt64 = 0
    Scanner(string: hexFormatted).scanHexInt64(&rgbValue)
    
    self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
              green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
              blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
              alpha: alpha)
}

你可以使用这个库

https://github.com/burhanuddin353/TFTColor

斯威夫特

UIColor.colorWithRGB(hexString: "FF34AE" alpha: 1.0)

objective - c

[UIColor colorWithRGBHexString:@"FF34AE" alpha:1.0f]

另一个实现允许字符串“FFF”或“FFFFFF”,并使用alpha:

+ (UIColor *) colorFromHexString:(NSString *)hexString alpha: (CGFloat)alpha{
    NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    if([cleanString length] == 3) {
        cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
                       [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                       [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                       [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
    }
    if([cleanString length] == 6) {
        cleanString = [cleanString stringByAppendingString:@"ff"];
    }

    unsigned int baseValue;
    [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];

    float red = ((baseValue >> 24) & 0xFF)/255.0f;
    float green = ((baseValue >> 16) & 0xFF)/255.0f;
    float blue = ((baseValue >> 8) & 0xFF)/255.0f;

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