UIColor from RGB/Hex color code

Write an extension in your Helper class, or any where

extension UIColor {
    convenience init(rgbValue: Int, alpha: CGFloat = 1.0) {
        self.init(red: ((CGFloat)((rgbValue & 0xFF0000) >> 16))/255.0, green: ((CGFloat)((rgbValue & 0x00FF00) >> 8))/255.0, blue: ((CGFloat)((rgbValue & 0x0000FF)))/255.0, alpha: alpha)
    }
}

Usage:

var color = UIColor.init(rgbValue: 0x2ECAD5)

—–

Alternatively, you can write a function:

static func UIColorFromRGB(_ rgbValue: Int) -> UIColor {
    return UIColor(red: ((CGFloat)((rgbValue & 0xFF0000) >> 16))/255.0, green: ((CGFloat)((rgbValue & 0x00FF00) >> 8))/255.0, blue: ((CGFloat)((rgbValue & 0x0000FF)))/255.0, alpha: 1.0)
}

Usage:

let color = UIColorFromRGB(0xff0000)

 

 


Also published on Medium.

By |2019-04-04T05:21:33+00:00March 14th, 2019|Categories: iOS Tips|0 Comments

Leave A Comment