天天看點

iOS開發:十六進制顔色轉UIColor

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];
}
           

使用

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)
    }
}
           

使用