Swift3.0 HexColor转UIColor

extension UIColor{

classfunchex(hex:String) ->UIColor{

varcolorString = hex.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines).uppercased()

if(colorString.hasPrefix("#")) {

letindex = colorString.index(colorString.startIndex, offsetBy:1)

colorString = colorString.substring(from: index)

}

if(colorString.characters.count!=6) {

returnUIColor.red

}

letredIndex = colorString.index(colorString.startIndex, offsetBy:2)

letredString = colorString.substring(to: redIndex)

letotherString = colorString.substring(from: redIndex)

letgreenIndex = otherString.index(otherString.startIndex, offsetBy:2)

letgreenString = otherString.substring(to: greenIndex)

letblueIndex = colorString.index(colorString.endIndex, offsetBy:-2)

letblueString = colorString.substring(from: blueIndex)

varred:CUnsignedInt=0, green:CUnsignedInt=0, blue:CUnsignedInt=0;

Scanner(string: redString).scanHexInt32(&red)

Scanner(string: greenString).scanHexInt32(&green)

Scanner(string: blueString).scanHexInt32(&blue)

returnUIColor(red:CGFloat(red) /255.0, green:CGFloat(green) /255.0, blue:CGFloat(blue) /255.0, alpha:CGFloat(1))

}

}

Demo:

lethexColor =UIColor.hex(hex:"#FFFFFF")

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容