美文网首页
转换十六进制 color 为 UIColor

转换十六进制 color 为 UIColor

作者: _浅墨_ | 来源:发表于2021-04-20 11:16 被阅读0次

将格式为#symbol 的十六进制(eg. #ffe700ff )颜色转换为 UIColor,可以这样写,代码如下:

extension UIColor {
    public convenience init?(hex: String) {
        let r, g, b, a: CGFloat

        if hex.hasPrefix("#") {
            let start = hex.index(hex.startIndex, offsetBy: 1)
            let hexColor = String(hex[start...])

            if hexColor.count == 8 {
                let scanner = Scanner(string: hexColor)
                var hexNumber: UInt64 = 0

                // #ffe700ff  分别代表 red, green, blue 以及 alpha
                if scanner.scanHexInt64(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                    g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                    b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                    a = CGFloat(hexNumber & 0x000000ff) / 255

                    self.init(red: r, green: g, blue: b, alpha: a)
                    return
                }
            }
        }

        return nil
    }
}

如果不带 alpha ,则代码可以这样:

extension UIColor {
    public convenience init?(hex: String) {
        let r, g, b : CGFloat

        if hex.hasPrefix("#") {
            let start = hex.index(hex.startIndex, offsetBy: 1)
            let hexColor = String(hex[start...])

            if hexColor.count == 6 {
                let scanner = Scanner(string: hexColor)
                var hexNumber: UInt64 = 0

                if scanner.scanHexInt64(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff0000) >> 16) / 255
                    g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255
                    b = CGFloat((hexNumber & 0x0000ff) ) / 255
                    self.init(red: r, green: g, blue: b, alpha: 1.0)
                    return
                }
            }
        }

        return nil
    }
}

使用方法示例:

let gold = UIColor(hex: "#ffe700ff")

相关文章

网友评论

      本文标题:转换十六进制 color 为 UIColor

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