convenience init(red: Int, green: Int, blue: Int , alp: CGFloat = 1.0 ) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alp)
}
convenience init(hexInt: Int) {
self.init(red:(hexInt >> 16) & 0xff, green:(hexInt >> 8) & 0xff, blue:hexInt & 0xff)
}
convenience init(hexString: String) {
var hexStr = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString
if (hexStr.hasPrefix("#")) {
hexStr = hexStr.substringFromIndex(hexStr.startIndex.advancedBy(1))
}
var hexInt: UInt32 = 0
NSScanner(string: hexStr).scanHexInt(&hexInt)
self.init(red: Int((hexInt >> 16) & 0xff), green: Int((hexInt >> 8) & 0xff), blue: Int(hexInt & 0xff)) }
}
extension UIColor {
// RGB整數(shù)設置顏色
convenience init(red: Int, green: Int, blue: Int , alp: CGFloat = 1.0 ) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alp)
}
// 16進制設置顏色
convenience init(hexInt: Int) {
self.init(red:(hexInt >> 16) & 0xff, green:(hexInt >> 8) & 0xff, blue:hexInt & 0xff)
}
// 字符串設置顏色
convenience init(hexString: String) {
var hexStr = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString
if (hexStr.hasPrefix("#")) {
hexStr = hexStr.substringFromIndex(hexStr.startIndex.advancedBy(1))
}
var hexInt: UInt32 = 0
NSScanner(string: hexStr).scanHexInt(&hexInt)
self.init(red: Int((hexInt >> 16) & 0xff), green: Int((hexInt >> 8) & 0xff), blue: Int(hexInt & 0xff))
}
}
UIColor(red: 253, green: 77, blue: 79)
UIColor(red: 253, green: 77, blue: 79, alp: 0.9)
UIColor(hexString: "#A94442")
UIColor(hexString: "#DCA7A7")
UIColor(hexInt: 0xdcdcdc)
UIColor(hexInt: 0xdcdaaa)
最后編輯于 :
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。