如何将RGB值转换为HEX字符串iOS swift

时间:2018-03-07 11:32:15

标签: ios swift uicolor

我想将RGB值转换为十六进制字符串。我将Hex转换为RGB如下,但我的反之亦然。

func hexStringToRGB(_ hexString: String) -> (red: CGFloat, green: CGFloat, blue: CGFloat) {
    var cString:String = hexString.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

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

    if ((cString.count) != 6) {
        return (red: 0.0, green: 0.0, blue: 0.0)
    }

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

    return (
        red: CGFloat((rgbValue & 0xFF0000) >> 16),
        green: CGFloat((rgbValue & 0x00FF00) >> 8),
        blue: CGFloat(rgbValue & 0x0000FF))
}

3 个答案:

答案 0 :(得分:5)

@Cristik是绝对正确的,除此之外,请在下面找到

使用此UIColor扩展类

extension UIColor {
    func toHexString() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0

        getRed(&r, green: &g, blue: &b, alpha: &a)

        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0

        return NSString(format:"#%06x", rgb) as String
    }

    convenience init(red: Int, green: Int, blue: Int) {
        assert(red >= 0 && red <= 255, "Invalid red component")
        assert(green >= 0 && green <= 255, "Invalid green component")
        assert(blue >= 0 && blue <= 255, "Invalid blue component")

        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
    }

}

你将以这种方式得到你的输出,

let color = UIColor(red: 1, green: 2, blue: 3, alpha: 1.0)
let hexString = color.toHexString()

print(hexString);

你的输出就是这个,

#fffefd

如有任何疑问,请与我联系。

答案 1 :(得分:2)

let rgbRedValue = 200
let rgbGreenValue = 13
let rgbBlueValue = 45

let hexValue = String(format:"%02X", Int(rgbRedValue)) + String(format:"%02X", Int(rgbGreenValue)) + String(format:"%02X", Int(rgbBlueValue))

另一种解决方法是将RGB转换为UIColor并从HEX获取UIColor字符串。

答案 2 :(得分:0)

斯威夫特4:

public static func rgbToHex(color: UIColor) -> String {

    var r:CGFloat = 0
    var g:CGFloat = 0
    var b:CGFloat = 0
    var a:CGFloat = 0
    color.getRed(&r, green: &g, blue: &b, alpha: &a)

    let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
    return String(format: "#%06x", rgb)
}