新建 Swift 文件,将Color 分类(下方代码 extension Color {}复制到文件中)即可。
使用方法:
1 含有透明度:
Color(hex: "#979797",alpha: 0.5)
2、不包含透明度
Color(hex: "#979797")
```
extension Color {
init(hex:String,alpha:Double=1.0) {
var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
hexSanitized = hexSanitized.replacingOccurrences(of:"#",with:"")
varrgb:UInt64=0
Scanner(string: hexSanitized).scanHexInt64(&rgb)
self.init(
.sRGB,
red:Double((rgb &0xFF0000) >>16) /255.0,
green:Double((rgb &0x00FF00) >>8) /255.0,
blue:Double(rgb &0x0000FF) /255.0,
opacity: alpha
)
}
}
```