swift5.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 } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章