在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 对【UIColor】进行扩展 1 import UIKit 2 3 extension UIColor { 4 5 // Hex String -> UIColor 6 convenience init(hexString: String) { 7 let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines) 8 let scanner = Scanner(string: hexString) 9 10 if hexString.hasPrefix("#") { 11 scanner.scanLocation = 1 12 } 13 14 var color: UInt32 = 0 15 scanner.scanHexInt32(&color) 16 17 let mask = 0x000000FF 18 let r = Int(color >> 16) & mask 19 let g = Int(color >> 8) & mask 20 let b = Int(color) & mask 21 22 let red = CGFloat(r) / 255.0 23 let green = CGFloat(g) / 255.0 24 let blue = CGFloat(b) / 255.0 25 26 self.init(red: red, green: green, blue: blue, alpha: 1) 27 } 28 29 // UIColor -> Hex String 30 var hexString: String? { 31 var red: CGFloat = 0 32 var green: CGFloat = 0 33 var blue: CGFloat = 0 34 var alpha: CGFloat = 0 35 36 let multiplier = CGFloat(255.999999) 37 38 guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { 39 return nil 40 } 41 42 if alpha == 1.0 { 43 return String( 44 format: "#%02lX%02lX%02lX", 45 Int(red * multiplier), 46 Int(green * multiplier), 47 Int(blue * multiplier) 48 ) 49 } 50 else { 51 return String( 52 format: "#%02lX%02lX%02lX%02lX", 53 Int(red * multiplier), 54 Int(green * multiplier), 55 Int(blue * multiplier), 56 Int(alpha * multiplier) 57 ) 58 } 59 } 60 } 测试示例: 1 // 16进制颜色 -> UIColor 2 let color = UIColor(hexString: "#A1A1A1") 3 print("UIColor:", color) 4 5 // UIColor -> 16进制颜色 6 let hexString = color.hexString 7 print("16进制颜色值:", hexString ?? "") 测试结果: 1 UIColor: UIExtendedSRGBColorSpace 0.631373 0.631373 0.631373 1 2 16进制颜色值: #A1A1A1
|
请发表评论