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 }
各個步驟:看看如何從十六進制字符串創建的UIColor,然後'UIColor'有一個屬性'CGColor'(這是使用的)。 – Larme