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


当前回答

你可以使用这个库

https://github.com/burhanuddin353/TFTColor

斯威夫特

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

objective - c

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

其他回答

使用Xcode的原生颜色文字功能来轻松地添加十六进制颜色。

在你的代码中输入颜色文字,然后让Xcode自动完成剩下的工作。

颜色选择界面将允许你粘贴十六进制颜色:#FF9300

宏的git差异将显示RGB值而不是十六进制值:

let orange = #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)

但它仍然是一种简单的方法来粘贴十六进制没有任何第三方工具或扩展。

我发现最简单的方法是使用宏。只要把它包括在你的标题中,它就可以在你的整个项目中使用。

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

Uicolor宏十六进制值

这段代码的格式化版本:

#define UIColorFromRGB(rgbValue) \
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
                green:((float)((rgbValue & 0x00FF00) >>  8))/255.0 \
                 blue:((float)((rgbValue & 0x0000FF) >>  0))/255.0 \
                alpha:1.0]

用法:

label.textColor = UIColorFromRGB(0xBC1128);

迅速:

static func UIColorFromRGB(_ rgbValue: Int) -> UIColor! {
    return UIColor(
        red: CGFloat((Float((rgbValue & 0xff0000) >> 16)) / 255.0),
        green: CGFloat((Float((rgbValue & 0x00ff00) >> 8)) / 255.0),
        blue: CGFloat((Float((rgbValue & 0x0000ff) >> 0)) / 255.0),
        alpha: 1.0)
}

十六进制初始化

extension UIColor{
public  convenience init(hex : String) {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
        self.init(red: 1, green: 1, blue: 1, alpha: 1)
        return
    }

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&rgbValue)

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


//Iniitailization
let myColor = UIColor(hex: "#452b4e")

编码愉快!享受! !

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

}

一个伟大的Swift实现(为Xcode 7更新)使用扩展,从各种不同的答案和地方拉到一起。在结尾还需要字符串扩展名。

Use:

let hexColor = UIColor(hex: "#00FF00")

注意:我添加了一个选项,为alpha通道的标准6位十六进制值的末尾添加2个额外的数字(传入值为00-99)。如果这冒犯了你,就把它拿掉。您可以实现它来传递一个可选的alpha参数。

扩展:

extension UIColor {

    convenience init(var hex: String) {
        var alpha: Float = 100
        let hexLength = hex.characters.count
        if !(hexLength == 7 || hexLength == 9) {
            // A hex must be either 7 or 9 characters (#RRGGBBAA)
            print("improper call to 'colorFromHex', hex length must be 7 or 9 chars (#GGRRBBAA)")
            self.init(white: 0, alpha: 1)
            return
        }

        if hexLength == 9 {
            // Note: this uses String subscripts as given below
            alpha = hex[7...8].floatValue
            hex = hex[0...6]
        }

        // Establishing the rgb color
        var rgb: UInt32 = 0
        let s: NSScanner = NSScanner(string: hex)
        // Setting the scan location to ignore the leading `#`
        s.scanLocation = 1
        // Scanning the int into the rgb colors
        s.scanHexInt(&rgb)

        // Creating the UIColor from hex int
        self.init(
            red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgb & 0x0000FF) / 255.0,
            alpha: CGFloat(alpha / 100)
        )
    }
}

字符串扩展: 浮动的来源 下标源

extension String {

    /**
    Returns the float value of a string
    */
    var floatValue: Float {
        return (self as NSString).floatValue
    }

    /**
    Subscript to allow for quick String substrings ["Hello"][0...1] = "He"
    */
    subscript (r: Range<Int>) -> String {
        get {
            let start = self.startIndex.advancedBy(r.startIndex)
            let end = self.startIndex.advancedBy(r.endIndex - 1)
            return self.substringWithRange(start..<end)
        }
    }
}