Hex color to UIColor

When your UX designer gives you a palette of Hexadecimal colors to assign at random to each user in the contact list and you already know that this color palette may change in the future, you start by breaking the problem into small parts.

Hexadecimal strings

Let’s assume that you load your Hex colors as strings from some file (in plain text with separators or in a JSON) and put them in an array.

Hex color in #FFFFFF format is in fact a 0xFFFFFF hexadecimal integer. So, the general idea behind the following code is to transform hexadecimal represented string value into an unsigned integer. In this way you can also reuse it in the other part of your code to more general purposes. The best way to do it is using NSScanner class and the corresponding scanHexInt: method.

As per documentation “The hexadecimal integer representation may optionally be preceded by 0x or 0X” we don’t need to check for 0x or 0X preceding the strings because scanHexInt: will do it for us and skip them automatically.

Returning result of this function is an NSArray with all you hex integer numbers converted from respective strings.

Random color from array

We must assign a random color to each contact, but to be associated and recognized by the user it must be the same for each application launch. We can surely generate a random number and save it somewhere in DB alongside contact data, but why complicate it so much if we can directly use contact data to do this?

For exercise wrap it in a function that receives a string to hash with the array of hex numbers and as a result return a hex integer.

Get the UIColor

The final step is to convert our hexadecimal color integer that we choose randomly into a valid UIColor. To do this you can write a dedicated function or #define a simple macro

And use it like this

or the full UIColorFromRGBA and specify also the desired Alpha value in [0, 255] range.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.