pmb pmb - 18 days ago 9
iOS Question

swift 3 convert string color to cgcolor

I am new on swift and iOS and there is something I don't know what should I do.

I have colors coming from backend and I want to convert it to

CGColor


"colors": [
"6909A1",
"7552D1",
"59B0DC",
"62E3CC"
],

func drawGradient(colors: [CGColor]) {
addLayer(colors: colors)
}


What should I do here to pass
CGColor
array after converting it from JSON.
I couldn't find the right solution how to get
CGColor
from simple String

Answer

UInt has an appropriate initializer to convert a hex string to its hex value

func color(from hexString : String) -> CGColor
{
  if let rgbValue = UInt(hexString, radix: 16) {
    let red   =  CGFloat((rgbValue >> 16) & 0xff) / 255
    let green =  CGFloat((rgbValue >>  8) & 0xff) / 255
    let blue  =  CGFloat((rgbValue      ) & 0xff) / 255
    return UIColor(red: red, green: green, blue: blue, alpha: 1.0).cgColor
  } else {
    return UIColor.black.cgColor
  }
}

Now map the string array to the color array

let hexColors = ["6909A1", "7552D1", "59B0DC", "62E3CC"]

let gradientColors = hexColors.map { color(from:$0) }

or alternatively in an UIColor extension

extension UIColor {

    convenience init(hexString : String)
    {
        if let rgbValue = UInt(hexString, radix: 16) {
            let red   =  CGFloat((rgbValue >> 16) & 0xff) / 255
            let green =  CGFloat((rgbValue >>  8) & 0xff) / 255
            let blue  =  CGFloat((rgbValue      ) & 0xff) / 255
            self.init(red: red, green: green, blue: blue, alpha: 1.0)
        } else {
            self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
        }
    }
}

let hexColors = ["6909A1", "7552D1", "59B0DC", "62E3CC"]

let gradientColors = hexColors.map { UIColor(hexString:$0).cgColor }