Anup Kanjariya
Anup Kanjariya

Reputation: 302

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

Upvotes: 3

Views: 12664

Answers (3)

Bilal
Bilal

Reputation: 312

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

Upvotes: 3

Saad Chaudhry
Saad Chaudhry

Reputation: 1412

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.

Upvotes: 6

PPL
PPL

Reputation: 6555

@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.

Upvotes: 15

Related Questions