advantis
10/28/2013 - 8:27 AM

UIColor from hex without string parsing, e.g. RGB(0x4C2BFF)

UIColor from hex without string parsing, e.g. RGB(0x4C2BFF)

//
//  Copyright © 2014 Yuri Kotov
//

import UIKit

public func RGB(color: UInt32) -> UIColor {
    let red = CGFloat(color >> 16 & 0xFF) / 255
    let green = CGFloat(color >> 8 & 0xFF) / 255
    let blue = CGFloat(color & 0xFF) / 255
    return UIColor(red: red, green: green, blue: blue, alpha: 1)
}

extension UIColor {
    class func colorFromHexString(string: String) -> UIColor? {
        var color: UInt32 = 0
        let scanner = NSScanner(string: string)
        return scanner.scanHexInt(&color) ? RGB(color) : nil
    }
}
//
//  Copyright © 2013 Yuri Kotov
//

NS_INLINE CGFloat ComponentValue(int color, int byte)
{
    return (color >> 8 * byte & 0xFF) / 255.f;
}

UIColor * RGB(int color)
{
    return [UIColor colorWithRed:ComponentValue(color, 2)
                           green:ComponentValue(color, 1)
                            blue:ComponentValue(color, 0)
                           alpha:1.f];
}
//
//  Copyright © 2013 Yuri Kotov
//

#import <UIKit/UIKit.h>

__attribute__((always_inline))
extern inline UIColor * RGB(int color);