很多时候都使用 #XXXXXX 这种16进制的颜色值,在ios中需要转换为 RGB
/// 转换 uicolor 颜色
func strConvertColor(colorStr:String , alpha:CGFloat = 1 ) -> UIColor {
//删除字符串中的空格
var str:String = colorStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if str.hasPrefix("0X"){
//如果是0x开头的,那么截取字符串,字符串从索引为2的位置开始,一直到末尾
let index = str.startIndex.advancedBy(2)
str = str.substringFromIndex(index)
}else if str.hasPrefix("#"){
//如果是#开头的,那么截取字符串,字符串从索引为1的位置开始,一直到末尾
let index = str.startIndex.advancedBy(1)
str = str.substringFromIndex(index)
}
if str.characters.count != 6 {
return UIColor.clearColor()
}
let rString = (str as NSString).substringToIndex(2)
let gString = ((str as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((str as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha )
}
来源:oschina
链接:https://my.oschina.net/u/2547410/blog/610229