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

问题描述:

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

I Want to convert RGB values to Hex string. I convert Hex to RGB as follow but how I do vice versa.

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

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 并从 UIColor 获取 HEX 字符串.

Another workaround could be to convert the RGB to UIColor and get the HEX string from UIColor.