我是swift和iOS的新手,有些东西我不知道该怎么做。
我的颜色来自后端,我想将其转换为CGColor
"colors": [
"6909A1",
"7552D1",
"59B0DC",
"62E3CC"
],
func drawGradient(colors: [CGColor]) {
addLayer(colors: colors)
}
在从JSON转换后,我应该怎么做才能传递CGColor
数组。
我找不到如何从简单的String
CGColor
的正确解决方案
答案 0 :(得分:4)
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 }
答案 1 :(得分:1)
不是太难,但是从十六进制字符串创建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)
}
}
}
答案 2 :(得分:0)
尝试这种方式
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)