Adjusting UIColor Luminosity in Swift
As part of expanding the colour palettes for our publications, the design team has been experimenting with taking the primary or brand colour and adjusting its luminosity. This has been used for backgrounds to highlight important page elements and provide some variation within article pages.
By no means am I an expert in colour models, but I had (wrongly) assumed that this functionality would be available as part of UIKit. UIKit provides the ability to alter the brightness of a colour, which sounds similar — however, after some research, it appears this is not the answer.
For this to make sense, there are two key definitions in colour spaces that need to be understood: HSL and HSV.
HSL: HSL stands for either Hue, Saturation, Luminosity, or Hue, Saturation, Lightness.
HSV: HSV is occasionally referred to as HSB and stands for Hue, Saturation, Value or Hue, Saturation, Brightness.
The key difference between the two is the final part, Luminosity vs Brightness.
Luminosity is often measured as a percentage, ranging from black (0%), through the colours set by Hue and Saturation, then to white (100%).
Brightness ranges from 0 to 100% (0 is always black and depending on the saturation, 100 may be white or a more or less saturated colour).
While the theory behind Hue and Saturation remains consistent enough, the difference between Luminosity and Brightness leads to wildly different results; as HSL provides a scale of black to white, whereas HSV provides a scale of black to a version of the colour you started with.
The image below shows what adjusting the Luminosity of a base colour can do, providing a much more varied palette that can be applied consistently across each publication.
Thanks to an incredibly helpful explanation from Nikolai Waldman, I was able to implement a Swift UIColor extension (below) that allows you to adjust the percentage of Luminosity for a colour.
The steps to convert are simple:
- Get the colour’s RGB values
- Convert the RGB values to HSL
- Adjust the Luminosity (0–100%)
- Calculate the RGB values for these new HSL values and build the new colour with them
An example of this can be seen in the new fact boxes that we have implemented in our article pages below. The fact boxes need to be prominent and appear separate from the rest of the article, meaning our usual background colours cannot be used.
The result is that we are able to use Luminosity to adjust our brand colours and provide an improved palette, without having to add a new colour for both light and dark mode across all 39 of our iOS publications, and any other variations that come up in the future. The screenshots above show the adjusted colours, using 12% Luminosity for dark mode and 95% Luminosity for light mode.