1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
convenience init?(hex : String, alpha : CGFloat = 1.0) { guard hex.characters.count >= 6 else { return nil } var tempHex = hex.uppercased() if tempHex.hasPrefix("0x") || tempHex.hasPrefix("##") || tempHex.hasPrefix("0X") { tempHex = tempHex.dropFirst(2) } if tempHex.hasPrefix("#") { tempHex = tempHex.dropFirst() } var range = NSRange(location: 0, length: 2) let rHex = (tempHex as NSString).substring(with: range) range.location = 2 let gHex = (tempHex as NSString).substring(with: range) range.location = 4 let bHex = (tempHex as NSString).substring(with: range) var r : UInt32 = 0, g : UInt32 = 0, b : UInt32 = 0 Scanner(string: rHex).scanHexInt32(&r) Scanner(string: gHex).scanHexInt32(&g) Scanner(string: bHex).scanHexInt32(&b) self.init(r : CGFloat(r), g : CGFloat(g), b : CGFloat(b)) }
convenience init(r : CGFloat, g : CGFloat, b : CGFloat, alpha : CGFloat = 1.0) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha) }
|