话不多说啊,直接上代码
import UIKit// MARK: 通过16进制初始化UIcolorextension UIcolor { convenIEnce init?(hexnum: Int) { self.init(hexStr: String(hexnum,radix: 16)) } convenIEnce init?(hexStr: String) { var hex = hexStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if hex.hasPrefix("#") { hex.remove(at: hex.startIndex) } if hex.hasPrefix("0x") || hex.hasPrefix(("0X")) { hex.removeSubrange((hex.startIndex ..< hex.index(hex.startIndex,offsetBy: 2))) } guard let hexnum = Int(hex,radix: 16) else { self.init() return nil } switch hex.characters.count { case 3: self.init(red: CGfloat(((hexnum & 0xF00) >> 8).duplicate4bits) / 255.0,green: CGfloat(((hexnum & 0x0F0) >> 4).duplicate4bits) / 255.0,blue: CGfloat((hexnum & 0x00F).duplicate4bits) / 255.0,Alpha: 1.0) case 4: self.init(red: CGfloat(((hexnum & 0xF000) >> 12).duplicate4bits) / 255.0,green: CGfloat(((hexnum & 0x0F00) >> 8).duplicate4bits) / 255.0,blue: CGfloat(((hexnum & 0x00F0) >> 4).duplicate4bits) / 255.0,Alpha: CGfloat((hexnum & 0x000F).duplicate4bits) / 255.0) case 6: self.init(red: CGfloat((hexnum & 0xFF0000) >> 16) / 255.0,green: CGfloat((hexnum & 0x00FF00) >> 8) / 255.0,blue: CGfloat((hexnum & 0x0000FF) >> 0) / 255.0,Alpha: 1.0) case 8: self.init(red: CGfloat((hexnum & 0xFF000000) >> 24) / 255.0,green: CGfloat((hexnum & 0x00FF0000) >> 16) / 255.0,blue: CGfloat((hexnum & 0x0000FF00) >> 8) / 255.0,Alpha: CGfloat(hexnum & 0x000000FF) / 255.0) default: self.init() return nil } } }private extension Int { var duplicate4bits: Int { return self << 4 + self }}
** 用法如下:**
let colorR = UIcolor(hexStr: "0xf00f")let colorG = UIcolor(hexStr: "0X0f0f")let colorB = UIcolor(hexStr: "#0fff")let colorRR = UIcolor(hexStr: "0xff0000ff")let colorGG = UIcolor(hexStr: "0X00ff00ff")let colorBB = UIcolor(hexStr: "#0000ffff")let colorRN = UIcolor(hexnum: 0xf00f)let colorGN = UIcolor(hexnum: 0x00ff00)let colorBN = UIcolor(hexnum: 0x0000ff)总结
以上是内存溢出为你收集整理的Swift 16进制编码转UIColor全部内容,希望文章能够帮你解决Swift 16进制编码转UIColor所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)