Swift 3 конвертирует цвет строки в cgcolor

Я новичок в Swift и iOS, и я не знаю, что мне делать.

У меня есть цвета, поступающие из бэкэнда, и я хочу преобразовать их в CGColor

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

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

Что мне делать, чтобы передать массив CGColor после его преобразования из JSON. Я не мог найти правильное решение, как получить CGColor из простой строки


person pmb    schedule 23.11.2016    source источник
comment
Различные шаги: посмотрите, как создать UIColor из шестнадцатеричной строки, тогда UIColor имеет свойство CGColor (это то, что нужно использовать).   -  person Larme    schedule 23.11.2016


Ответы (3)


UInt имеет удобный инициализатор для преобразования шестнадцатеричной строки в ее шестнадцатеричное значение.

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

Теперь сопоставьте массив строк с массивом цветов.

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

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

или альтернативно в расширении UIColor

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 }
person vadian    schedule 23.11.2016
comment
Спасибо @vadian. Это именно то, что я ищу - person pmb; 23.11.2016

Не слишком сложно, но возможность создавать объекты UIColor/CGColor из шестнадцатеричных строк не встроена в Swift. Однако вы можете просто поместить это расширение в свой проект, чтобы добавить его:

extension UIColor {
    public convenience init?(hexString: String) {
        let r, g, b, a: CGFloat

        if hexString.hasPrefix("#") {
            let start = hexString.index(hexString.startIndex, offsetBy: 1)
            let hexColor = hexString.substring(from: start)

            if hexColor.characters.count == 8 {
                let scanner = Scanner(string: hexColor)
                var hexNumber: UInt64 = 0

                if scanner.scanHexInt64(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                    g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                    b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                    a = CGFloat(hexNumber & 0x000000ff) / 255

                    self.init(red: r, green: g, blue: b, alpha: a)
                    return
                }
            }
        }

        return nil
    }
}

Затем вы можете сделать что-то подобное, чтобы преобразовать этот шестнадцатеричный массив цветов в массив CGColor:

func convertColours() {
    let stringColours = ["6909A1",
                         "7552D1",
                         "59B0DC",
                         "62E3CC"]
    var colours = [CGColor]()

    for stringColour in stringColours {
        if let colour = UIColor(hexString: stringColour) {
            colours.append(colour.cgColor)
        }
    }        
}
person Jacob King    schedule 23.11.2016

Попробуйте этот способ

extension UIColor {
    convenience init(red: Int, green: Int, blue: Int) {
        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
    }

    func color(with hex: Int) -> CGColor {
        let color = UIColor(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff)
        return color.cgColor
    }
}
UIColor().color(with: Int(stringColours[0], radix: 16)!)
UIColor().color(with: 0x333333)
person J. Koush    schedule 23.11.2016