美文网首页
swift 4.0利用Scanner根据十六进制颜色创建UICo

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

作者: 菲菲的青青 | 来源:发表于2018-08-06 14:18 被阅读0次

    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根据十六进制颜色创建UICo

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