1、比如 rgb 色值为 55、 186 、89 那么给 UIColor 设置里面要除以 255
UIColor(red: 55/255, green: 186/255, blue: 89/255, alpha: 0.5)
2、设置 16 进制颜色也同上
UIColor(red: 0x37/255, green: 0xba/255, blue: 0x46/255, alpha: 0.5)
对 UIColor 进行扩展
import UIKit
//UIColor扩展
extension UIColor {
//使用rgb方式生成自定义颜色
convenience init(_ r : CGFloat, _ g : CGFloat, _ b : CGFloat)
{
let red = r / 255.0
let green = g / 255.0
let blue = b / 255.0
self.init(red: red, green: green, blue: blue, alpha: 1)
}
//使用rgba方式生成自定义颜色
convenience init(_ r : CGFloat, _ g : CGFloat, _ b : CGFloat, _ a : CGFloat)
{
let red = r / 255.0
let green = g / 255.0
let blue = b / 255.0
self.init(red: red, green: green, blue: blue, alpha: a)
}
//16进制生成自定义颜色
class func hexColorWithAlpha(color: String, alpha:CGFloat) -> UIColor
{
var colorString = color.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if colorString.count < 6 {
return UIColor.clear
}
if colorString.hasPrefix("0x") {
colorString = (colorString as NSString).substring(from: 2)
}
if colorString.hasPrefix("#") {
colorString = (colorString as NSString).substring(from: 1)
}
if colorString.count < 6 {
return UIColor.clear
}
var rang = NSRange()
rang.location = 0
rang.length = 2
let rString = (colorString as NSString).substring(with: rang)
rang.location = 2
let gString = (colorString as NSString).substring(with: rang)
rang.location = 4
let bString = (colorString as NSString).substring(with: rang)
var r:UInt64 = 0, g:UInt64 = 0,b: UInt64 = 0
Scanner(string: rString).scanHexInt64(&r)
Scanner(string: gString).scanHexInt64(&g)
Scanner(string: bString).scanHexInt64(&b)
return UIColor.init(CGFloat(r), CGFloat(g), CGFloat(b), alpha)
}
}
这样我们初始化的时候就不用在手动除以 255 了。
//RGB
UIColor(55, 186, 8)
UIColor(0x37, 0xba, 0x46)
//RGBA
UIColor(55, 186, 8, 0.5)
UIColor(0x37, 0xba, 0x46, 0.5)
UIColor.hexColorWithAlpha(color: "#D4D5D6", alpha: 1.0)
网友评论