有时候我们需要从一个16进制的颜色代码(例如#fafcfe)获得一个颜色对象,可以使用如下方法:
func hexColorString(_ color:String,alpha:Float=1.0)->UIColor{
var colorString=color.trimmingCharacters(in:.whitespacesAndNewlines).lowercased()
if colorString.characters.count<6{
return UIColor.clear
}
if colorString.hasPrefix("0x"){
colorString=colorString.replacingOccurrences(of: "0x", with: "")
}
else if colorString.hasPrefix("#"){
colorString=colorString.replacingOccurrences(of: "#", with: "")
}
if colorString.characters.count != 6{
return UIColor.clear
}
let colorStr=NSString(string:colorString)
var range=NSRange(location: 0,length: 2)
let redString=colorStr.substring(with: range)
range.location = 2
let greenString=colorStr.substring(with: range)
range.location = 4
let blueString=colorStr.substring(with: range)
var red:UInt32=0
var green:UInt32=0
var blue:UInt32=0
var success=Scanner(string: redString).scanHexInt32(&red)
if !success{
return UIColor.clear
}
success=Scanner(string: greenString).scanHexInt32(&green)
if !success{
return UIColor.clear
}
success=Scanner(string: blueString).scanHexInt32(&blue)
if !success{
return UIColor.clear
}
return UIColor(red:CGFloat(red)/255,green:CGFloat(green)/255,blue:CGFloat(blue)/255,alpha:CGFloat(alpha))
}
如果希望从r,g,b三原色获得颜色对象则可以使用如下方法:
func color(_ red:UInt8,green:UInt8,blue:UInt8,alpha:UInt8=0xff)->UIColor{
return UIColor(red:CGFloat(red)/255,green:CGFloat(green)/255,blue:CGFloat(blue)/255,alpha:CGFloat(alpha)/255)
}
网友评论