swift UIColor使用Hex String创建

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift UIColor使用Hex String创建相关的知识,希望对你有一定的参考价值。

extension UIColor {

    convenience init(hex: String) {
        let hexStr = hex.lowercased().replacingOccurrences(of: "0x", with: "")
        let hexmap = hexStr.map { String($0) }
            + Array(repeating: "0", count: max(6 - hexStr.count, 0))
            + Array(repeating: "f", count: max(8 - max(6, hexStr.count), 0))
        let split = stride(from: 0, to: hexmap.count, by: 2)
            .map { hexmap[$0..<$0+2]
                .reduce(into: String()) { $0 += $1 } }
        let hexRGB = split.map { CGFloat(Int($0, radix: 16) ?? 0) / 255.0 }
        self.init(red: hexRGB[0],
                  green: hexRGB[1],
                  blue: hexRGB[2],
                  alpha: hexRGB[3])
    }

}

以上是关于swift UIColor使用Hex String创建的主要内容,如果未能解决你的问题,请参考以下文章

swift Hex到UIcolor

swift Hex到UIColor

swift Hex到UIColor

swift UIColor + hex

swift—UIColor十六进制

swift—UIColor十六进制