swift3 十六进制颜色转换为 UIColor

可以通过以下两种方式转换,原理都是一样的,只是使用方式不一样。

String 添加扩展

extension String {
    func uicolor(alpha: CGFloat = 1.0) -> UIColor {
        // 存储转换后的数值
        var red: UInt32 = 0, green: UInt32 = 0, blue: UInt32 = 0
        var hex = self
        // 如果传入的十六进制颜色有前缀,去掉前缀
        if hex.hasPrefix("0x") || hex.hasPrefix("0X") {
            hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 2))
        } else if hex.hasPrefix("#") {
            hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 1))
        }
        // 如果传入的字符数量不足6位按照后边都为0处理,当然你也可以进行其它操作
        if characters.count < 6 {
            for _ in 0..<6-characters.count {
                hex += "0"
            }
        }
        
        // 分别进行转换
        // 红
        Scanner(string: hex.substring(to: hex.index(hex.startIndex, offsetBy: 2))).scanHexInt32(&red)
        // 绿
        Scanner(string: hex.substring(with: hex.index(hex.startIndex, offsetBy: 2)..
调用
"FF0000".uicolor() // red

UIColor 添加扩展(实际代码还是那些)

extension UIColor {

    /// 用十六进制颜色创建UIColor
    ///
    /// - Parameter hexColor: 十六进制颜色
    /// - Parameter hexColor: 透明度
    convenience init(hexColor: String, alpha: CGFloat = 1.0) {

        // 存储转换后的数值
        var red: UInt32 = 0, green: UInt32 = 0, blue: UInt32 = 0
        var hex = self
        // 如果传入的十六进制颜色有前缀,去掉前缀
        if hex.hasPrefix("0x") || hex.hasPrefix("0X") {
            hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 2))
        } else if hex.hasPrefix("#") {
            hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 1))
        }
        // 如果传入的字符数量不足6位按照后边都为0处理,当然你也可以进行其它操作
        if characters.count < 6 {
            for _ in 0..<6-characters.count {
                hex += "0"
            }
        }
        
        // 分别进行转换
        // 红
        Scanner(string: hex.substring(to: hex.index(hex.startIndex, offsetBy: 2))).scanHexInt32(&red)
        // 绿
        Scanner(string: hex.substring(with: hex.index(hex.startIndex, offsetBy: 2)..
调用
UIColor(hexColor: "FF0000") // red

你可能感兴趣的:(swift3 十六进制颜色转换为 UIColor)