返回 导航

Swift

hangge.com

Swift - 十六进制颜色字符串与UIColor之间的相互转换(附样例)

作者:hangge | 2019-03-08 08:11
    有时我们需要通过 16 进制颜色字符串(比如:#C0C0C0)来初始化 UIColor,或者将 UIColor 转成 16 进制字符串打印或显示出来。下面通过样例演示这个转换如何实现。

1,扩展 UIColor

为方便使用,我们首先对 UIColor 进行扩展(UIColor+.swift),增加相关的转换方法和属性。
import UIKit

extension UIColor {
    
    // Hex String -> UIColor
    convenience init(hexString: String) {
        let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        
        if hexString.hasPrefix("#") {
            scanner.scanLocation = 1
        }
        
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)
        
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        
        self.init(red: red, green: green, blue: blue, alpha: 1)
    }
    
    // UIColor -> Hex String
    var hexString: String? {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        
        let multiplier = CGFloat(255.999999)
        
        guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
            return nil
        }
        
        if alpha == 1.0 {
            return String(
                format: "#%02lX%02lX%02lX",
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier)
            )
        }
        else {
            return String(
                format: "#%02lX%02lX%02lX%02lX",
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier),
                Int(alpha * multiplier)
            )
        }
    }
}

2,使用样例

(1)样例代码
import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 16进制颜色 -> UIColor
        let color = UIColor(hexString: "#C0C0C0")
        print("UIColor:", color)
        
        // UIColor -> 16进制颜色
        let hexString = color.hexString
        print("16进制颜色值:", hexString ?? "")
    }
}

(2)运行结果如下:
评论

全部评论(0)

回到顶部