Swift String to UIColor (支持3,4,6,8长度的16进制颜色值)

前端之家收集整理的这篇文章主要介绍了Swift String to UIColor (支持3,4,6,8长度的16进制颜色值)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import UIKit
extension UIColor {
public convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat 0
var blue: CGFloat 0
var alpha: CGFloat 10
if rgba.hasPrefix("#") {
let index = advance(rgba.startIndex,1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (count(hex)) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 150
green & 0x0F0) 4) 0
blue = CGFloat(hexValue & 0x00F) 0
4:
& 0xF000) 12) 0
& 0x0F00) 0
& 0x00F0) 0
alpha & 0x000F) 0
6:
& 0xFF0000) 16) 2550
& 0x00FF00) 0
& 0x0000FF) 0
8:
& 0xFF000000) 24) 0
& 0x00FF0000) 0
& 0x0000FF00) 0
& 0x000000FF) 0
default:
print("Invalid RGB string,number of characters after '#' should be either 3,4,6 or 8")
}
} else {
println("Scan hex error")
}
else {
")
}
self.init(red:red,green:green,blue:blue,alpha:alpha)
}
}
原文链接:/swift/326506.html

猜你在找的Swift相关文章