Swift 解析16进制颜色

前端之家收集整理的这篇文章主要介绍了Swift 解析16进制颜色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Swift 版 解析16进制颜色

extension UIColor {

    public convenience init(hex: String) {

        var red:   CGFloat = 0.0
        var green: CGFloat = 0.0
        var blue:  CGFloat = 0.0
        var alpha: CGFloat = 1.0
        var hex:   String = hex

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

        let scanner = Scanner(string: hex)
        var hexValue: CUnsignedLongLong = 0
        @H_301_21@if scanner.scanHexInt64(&hexValue) {
            @H_301_21@switch (hex.count) {
            @H_301_21@case 3:
                red   = CGFloat((hexValue & 0xF00) >> 8)       / 15.0
                green = CGFloat((hexValue & 0x0F0) >> 4)       / 15.0
                blue  = CGFloat(hexValue & 0x00F)              / 15.0
            @H_301_21@case 4:
                red   = CGFloat((hexValue & 0xF000) >> 12)     / 15.0
                green = CGFloat((hexValue & 0x0F00) >> 8)      / 15.0
                blue  = CGFloat((hexValue & 0x00F0) >> 4)      / 15.0
                alpha = CGFloat(hexValue & 0x000F)             / 15.0
            @H_301_21@case 6:
                red   = CGFloat((hexValue & 0xFF0000) >> 16)   / 255.0
                green = CGFloat((hexValue & 0x00FF00) >> 8)    / 255.0
                blue  = CGFloat(hexValue & 0x0000FF)           / 255.0
            @H_301_21@case 8:
                red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
                green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
                blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
                alpha = CGFloat(hexValue & 0x000000FF)         / 255.0
            @H_301_21@default:
                print("Invalid RGB string,number of characters after '#' should be either 3,4,6 or 8",terminator: "")
            }
        } @H_301_21@else {
            print("Scan hex error")
        }
        @H_301_21@self.init(red:red,green:green,blue:blue,alpha:alpha)
    }

}

使用方式

@H_301_21@let _ = UIColor(hex: "#eeeeee")

猜你在找的Swift相关文章