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)

    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容