Color Utilities

20 Nov 2018

I was creating some demonstration code for a talk recently about working with binary and hex numbers in a Swfit project. After the talk, more than one person seemed more interested in the demo code than the other parts of the talk. The demo code was a quick utility to convert from the color values that a designer often provides (web hex values) to the corresponding UIColor values. I have cleaned up the code and repackaged it as a Swift playground for use in your project. Please remember to retain my copyright in the source code if you use it.

The basic function

At it’s most basic, we can take a hex value that a designer provides. Usually something like “#3F23D7”, remove the “#” and then convert the hex value to a UInt value. To convert from a string representation of a number to the underlying number, the system provides a handy set of utilities and one is called strtoul which stands for STRingTOUnsignedLong. These conversion functions are in the base C libraries in the OS. So, using the man strtoul command in Terminal is the best way to learn more about this one and the variations for the other types of numbers. I’ve included a link here to manpages.org, but since this is a generic site, asking Terminal for the information is going to give you better results. strtoul takes a string representing the number as a parameter and also takes an integer representing the base as another parameter. It takes a third parameter, but we are going to leave it as nil for this demo.

let converted = strtoul("3F23d7", nil, 16)
//converted will now be a unsigned integer with a value of 4137943

Something important to note, strtoul does not return any error. If it cannot convert the string it will return 0.

Now that we have an integer, we can use bitwise operators to move and mask the three values out of the original number. I have a longer discussion of bitwise operators in this post.

func colorWith(hex: UInt, alpha: CGFloat = 1.0) -> UIColor {
    let red: CGFloat = CGFloat((hex >> 16) & 0xFF) / 0xFF
    let green: CGFloat = CGFloat((hex >> 8) & 0xFF) / 0xFF
    let blue: CGFloat = CGFloat(hex & 0xFF) / 0xFF
    return UIColor.init(red: red, green: green, blue: blue, alpha: alpha)
}

By default, the code assumes an alpha of 1.0. However, if a designer provides an alpha (“tranparency”) of less than 100%, we can convert it to a hex value and pass it in, or else inject it anywhere along the way. If all of that proves too difficult, we have our old fallback of the system extension to UIColor

let myColor = UIColor.blue
let moreTransparent = myColor.withAlphaComponent(CGFloat(0.33))

The Playground

The playground for this demo is linked here as ColorConvert.playground. The playground contains three functions that each take one step of the process. So, use whichever function makes the most sense given how the designer is providing color values.