[Swift]扩展UIColor:实现十六进制颜色字符串与UIColor之间的相互转换

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/ )
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10647238.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

对【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

 

转载于:https://www.cnblogs.com/strengthen/p/10647238.html

你可能感兴趣的:([Swift]扩展UIColor:实现十六进制颜色字符串与UIColor之间的相互转换)