Objective-c 版本
UIColor * __nullable UIColorFromHexValue(NSUInteger hexValue) {
CGFloat red = (hexValue & 0xFF0000) >> 16;
CGFloat green = (hexValue & 0x00FF00) >> 8;
CGFloat blue = hexValue & 0x0000FF;
return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1.0];
}
使用
// 复制上面代码放在任意头文件中,并引用该头文件,在需要的地方调用如下
UIColor *color = UIColorFromHexValue(0xFFFFFF);
Swift 版本
extension UIColor {
static func hex(_ hexValue: UInt) -> UIColor {
let red = (hexValue & 0xFF0000) >> 16
let green = (hexValue & 0x00FF00) >> 8
let blue = hexValue & 0x0000FF
return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)
}
}
使用
let color = UIColor.hex(0xFFFFFF);
还不快抢沙发