Hello guys here in this article we are going to learn about converting Hex to UIColor.
First we are creating extension to UIColor as following:
Next add the following two methods inside the color extension as below:
We are done for converting Hex to UIColor.
Lets take the following hex value:
Take Silver with hex value as #C0C0C0.
For converting the above hex value add the following line at the start of extension:
That's it now we can use silver color as follow:
That's it we can use now as the follow:
First we are creating extension to UIColor as following:
extension UIColor { // Code }
Next add the following two methods inside the color extension as below:
// Create a UIColor from RGB convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) { self.init( red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: a ) } // Create a UIColor from a hex value (E.g 0xC0C0C0) convenience init(hex: Int, a: CGFloat = 1.0) { self.init( red: (hex >> 16) & 0xFF, green: (hex >> 8) & 0xFF, blue: hex & 0xFF, a: a ) }
We are done for converting Hex to UIColor.
Lets take the following hex value:
Take Silver with hex value as #C0C0C0.
For converting the above hex value add the following line at the start of extension:
static let silver = UIColor(hex: 0xC0C0C0)
That's it now we can use silver color as follow:
let silver = UIColor.silver
Conclusion:
If you are confused, forget above all lines of code. Simply add the following code :extension UIColor { // Create a UIColor from RGB convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) { self.init( red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: a ) } // Create a UIColor from a hex value (E.g 0x000000) convenience init(hex: Int, a: CGFloat = 1.0) { self.init( red: (hex >> 16) & 0xFF, green: (hex >> 8) & 0xFF, blue: hex & 0xFF, a: a ) } }
That's it we can use now as the follow:
let silver = UIColor(hex: 0xC0C0C0)
No comments:
Post a Comment