我使用以下内容将hex转换为rgb,将rgb转换为hex。
extension UIColor {
convenience init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 0
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let r = (rgbValue & 0xff0000) >> 16
let g = (rgbValue & 0xff00) >> 8
let b = rgbValue & 0xff
self.init(
red: CGFloat(r) / 0xff,
green: CGFloat(g) / 0xff,
blue: CGFloat(b) / 0xff, alpha: 1
)
}
func toHexString() -> String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return String(format: "%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
}
}
UIColor init(hex:String)
工作正常但是当我尝试从UIColor
获取十六进制时,它总是返回一个超过6个字符的字符串,如" D7FFFFFFFFE9"。任何人都可以在代码中指出问题吗?