简体   繁体   中英

How to convert RGB values to HEX string iOS swift

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

@Cristik is absolutely right, on top of that please find below also

Use this UIColor extension class,

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

}

and you will get your output this way,

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

print(hexString);

Your output will be this,

#fffefd

Let me know in case of any queries.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM