美文网首页iOS Developer
swift3 十六进制颜色转换为 UIColor

swift3 十六进制颜色转换为 UIColor

作者: CoderAzreal | 来源:发表于2017-06-17 23:31 被阅读0次

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

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)..<hex.index(hex.startIndex, offsetBy: 4))).scanHexInt32(&green)
        // 蓝
        Scanner(string: hex.substring(from: hex.index(startIndex, offsetBy: 4))).scanHexInt32(&blue)
        
        return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alpha)
    }
}
调用
"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)..<hex.index(hex.startIndex, offsetBy: 4))).scanHexInt32(&green)
        // 蓝
        Scanner(string: hex.substring(from: hex.index(startIndex, offsetBy: 4))).scanHexInt32(&blue)

        self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alpha)
    }
}
调用
UIColor(hexColor: "FF0000") // red

相关文章

网友评论

    本文标题:swift3 十六进制颜色转换为 UIColor

    本文链接:https://www.haomeiwen.com/subject/gywbqxtx.html