swift-3.0 将HexColor转变为UIColor的方法
2017-01-06 17:31
363 查看
swift-3.0 将HexColor转变为UIColor的方法
// MARK:- 把#ffffff颜色转为UIColor
extension UIColor {
class func colorWithHexString(hex:String) ->UIColor {
var cString = hex.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
let index = cString.index(cString.startIndex, offsetBy:1)
cString = cString.substring(from: index)
}
if (cString.characters.count != 6) {
return UIColor.red
}
let rIndex = cString.index(cString.startIndex, offsetBy: 2)
let rString = cString.substring(to: rIndex)
let otherString = cString.substring(from: rIndex)
let gIndex = otherString.index(otherString.startIndex, offsetBy: 2)
let gString = otherString.substring(to: gIndex)
let bIndex = cString.index(cString.endIndex, offsetBy: -2)
let bString = cString.substring(from: bIndex)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
}
// MARK:- 把#ffffff颜色转为UIColor
extension UIColor {
class func colorWithHexString(hex:String) ->UIColor {
var cString = hex.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
let index = cString.index(cString.startIndex, offsetBy:1)
cString = cString.substring(from: index)
}
if (cString.characters.count != 6) {
return UIColor.red
}
let rIndex = cString.index(cString.startIndex, offsetBy: 2)
let rString = cString.substring(to: rIndex)
let otherString = cString.substring(from: rIndex)
let gIndex = otherString.index(otherString.startIndex, offsetBy: 2)
let gString = otherString.substring(to: gIndex)
let bIndex = cString.index(cString.endIndex, offsetBy: -2)
let bString = cString.substring(from: bIndex)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
}
相关文章推荐
- Swift3.0对UIColor进行方法扩展
- Swift 3.0封装 URLSession 的GET/SET方法代替 Alamofire
- Swift 3.0 延迟加载的几种实现方法
- swift3.0最新拨打电话方法
- iOS ScrollView实现自动布局的方法(适用Swift 3.0 )
- swift3.0把#ffffff或者ffffff格式转为UIColor的方法
- 三十 Swift3.0之 构造方法 二
- 二十六 Swift3.0之 方法
- Swift - 2.3的代码到3.0的转变
- swift3.0 协议内方法声明为mutating
- Swift3.0 -- didSet(OC中重写setter方法)
- 三十一 Swift3.0之 析构方法
- Swift3.0 中代理的使用方法
- Swift 3.0中GCD的常用方法
- iOS UI调试工具Reveal lldb配置方法(Swift3.0工程)
- swift3.0中String.Index截取字符串方法,很方便哦
- iOS ScrollView 下拉放大图片,上滑覆盖图片实现方法(Swift 3.0)
- Swift 3.0 延迟加载实现方法。
- Swift3.0中文教程:11.方法
- Swift 3.0将UILabel数字颜色设置为红色的方法