extension UIcolor { public convenIEnce init(hex: String) { var red: CGfloat = 0.0 var green: CGfloat = 0.0 var blue: CGfloat = 0.0 var Alpha: CGfloat = 1.0 var hex: String = hex if hex.hasPrefix("#") { let index = hex.index(hex.startIndex,offsetBy: 1) hex = String(hex[index...]) } let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch (hex.count) { case 3: red = CGfloat((hexValue & 0xF00) >> 8) / 15.0 green = CGfloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGfloat(hexValue & 0x00F) / 15.0 case 4: red = CGfloat((hexValue & 0xF000) >> 12) / 15.0 green = CGfloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGfloat((hexValue & 0x00F0) >> 4) / 15.0 Alpha = CGfloat(hexValue & 0x000F) / 15.0 case 6: red = CGfloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGfloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGfloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGfloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGfloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGfloat((hexValue & 0x0000FF00) >> 8) / 255.0 Alpha = CGfloat(hexValue & 0x000000FF) / 255.0 default: print("InvalID RGB string,number of characters after '#' should be either 3,4,6 or 8",terminator: "") } } else { print("Scan hex error") } self.init(red:red,green:green,blue:blue,Alpha:Alpha) }}使用方式
let _ = UIcolor(hex: "#eeeeee")总结
以上是内存溢出为你收集整理的Swift 解析16进制颜色全部内容,希望文章能够帮你解决Swift 解析16进制颜色所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)