swift5.0根据十六进制获取颜色

2020-07-17  本文已影响0人  千年积木
extension UIColor{
    // MARK: - 根据十六进制获取颜色
    class func RGB_HEX(_ rgbValue: String) -> UIColor? {
           
           ///  支持格式包括: #ff21af64   #21af64   0x21af64
           if (rgbValue.hasPrefix("#") || (rgbValue.hasPrefix("0x"))) {
               let mutStr = (rgbValue as NSString).mutableCopy() as! NSMutableString
               
               if (rgbValue.hasPrefix("#")) {
                   mutStr.deleteCharacters(in: NSRange.init(location: 0, length: 1))
               } else {
                   mutStr.deleteCharacters(in: NSRange.init(location: 0, length: 2))
               }
               
               if (mutStr.length == 6) {
                   mutStr.insert("ff", at: 0)
               }
               
               
               let aStr = mutStr.substring(with: NSRange.init(location: 0, length: 2))
               let rStr = mutStr.substring(with: NSRange.init(location: 2, length: 2))
               let gStr = mutStr.substring(with: NSRange.init(location: 4, length: 2))
               let bStr = mutStr.substring(with: NSRange.init(location: 6, length: 2))
               
               let alpha = aStr.hexValue()
               let red = rStr.hexValue()
               let green = gStr.hexValue()
               let blue = bStr.hexValue()
               
               return UIColor.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha) / 255.0)
           }else{
               assert(false, "16进制字符串转UIColor:格式不支持")
               return nil
           }
       }
}

extension String{
    /// MARK: - 获取十六进制的值
    func hexValue() -> Int {
        let str = self.uppercased()
        var sum = 0
        for i in str.utf8 {
            sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
            if i >= 65 {                 // A-Z 从65开始,但有初始值10,所以应该是减去55
                sum -= 7
            }
        }
        return sum
    }
}

上一篇 下一篇

猜你喜欢

热点阅读