swift 4.0利用Scanner根据十六进制颜色创建UIColor

swift 4.0利用Scanner根据十六进制颜色创建UIColor

首先创建一个UIColor的extension类

/// 用十六进制颜色创建UIColor

    /// - Parameter hexColor: 十六进制颜色 (0F0F0F)

    convenience init(hexColor: String) {

        // 存储转换后的数值

        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0

        // 分别转换进行转换

        var currentHexColor:String = hexColor

        if hexColor.hasPrefix("#") {  //截取字符串 去调#号

            let index =  currentHexColor.index(currentHexColor.startIndex, offsetBy: 1)

            currentHexColor = String(currentHexColor[index...])

        }

        if currentHexColor.count >= 8 {

            var alpha:UInt32 = 0

            Scanner(string: currentHexColor[0..<2]).scanHexInt32(&alpha)

            Scanner(string: currentHexColor[2..<4]).scanHexInt32(&red)

            Scanner(string: currentHexColor[4..<6]).scanHexInt32(&green)

            Scanner(string: currentHexColor[6..<8]).scanHexInt32(&blue)

            self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha)/255.0)

            return

        }

        Scanner(string: currentHexColor[0..<2]).scanHexInt32(&red)

        Scanner(string: currentHexColor[2..<4]).scanHexInt32(&green)

        Scanner(string: currentHexColor[4..<6]).scanHexInt32(&blue)

        self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)

    }

你可能感兴趣的:(swift 4.0利用Scanner根据十六进制颜色创建UIColor)