extension UIColor {
class func RGBColor(r :CGFloat, g :CGFloat, b :CGFloat, a :CGFloat) -> UIColor {
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
class func HexColor(hex: UInt) -> (UIColor) {
let r = (CGFloat)((hex >> 16) & 0xFF)
let g = (CGFloat)((hex >> 8) & 0xFF)
let b = (CGFloat)((hex) & 0xFF)
return RGBColor(r: r, g: g, b: b, a: 1)
}
class func HexColor(hexStr: String) -> UIColor{
var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0
var prefixCount = 0
if hexStr.hasPrefix("0x") || hexStr.hasPrefix("0X") {
prefixCount = 2
}
if hexStr.hasPrefix("#") {
prefixCount = 1
}
// subString扩展方法请看下文
let subStrR = hexStr.subString(from: (0+prefixCount), length: 2)
let subStrG = hexStr.subString(from: (2+prefixCount), length: 2)
let subStrB = hexStr.subString(from: (4+prefixCount), length: 2)
Scanner(string: subStrR).scanHexInt32(&red)
Scanner(string: subStrG).scanHexInt32(&green)
Scanner(string: subStrB).scanHexInt32(&blue)
return UIColor.RGBColor(r: CGFloat(red), g: CGFloat(green), b: CGFloat(blue), a: 1.0)
}
}
一个截取字符串的扩展
extension String {
//MARK: - 字符串截取(从0开始计数)
func subString(from: Int, length: Int) -> String {
if (from >= 0) && (length>0) && (self.characters.count>=(from+length)){
let start = self.index(self.startIndex, offsetBy: from)
let len = self.index(start, offsetBy: length-1)
let subStr = self[start...len]
return subStr
}
XGLog(message: "字符串截取越界!")
return ""
}
}