I was looking to be able to turn any UIColor into a gradient. The way I am intending to do this is by using Core Graphics to draw a gradient. What I am trying to do is to get a color, lets say:
[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
and get a UIColor which is a few shades darker and a few shades lighter. Does anyone know how to do this? Thank you.
Tested in Xcode 10 with Swift 4.x for iOS 12
Start with your color as a UIColor and pick a darkening factor (as a CGFloat)
The type CGColor has an optional value
components
which break down the color into RGBA (as a CGFloat array with values between 0 and 1). You can then reconstruct a UIColor using RGBA values taken from the CGColor and manipulate them.In this example, each of the RGB valuse were divided by 2, making the color half as dark as it was before. The alpha value remained the same, but you could alternatively apply the darken factor on the alpha value rather than the RGB.
Ideally, the functions should be encapsulated inside a
UIColor
extension called,UIColor+Brightness.swift
, and have a configurable brightness - see example below:I render coloured cells based on a status value:
For this I wrote a swift extension based on some old objc code after I got an error using CryingHippo's suggestion:
The same works for
NSColor
as well. Simply replaceUIColor
withNSColor
.TL;DR:
Swift:
Usage:
Objective-C:
@rchampourlier was right in his comment to @user529758 (The accepted answer) - The HSB (Or HSV) and RGB solutions give completely different results. RGB just adds (Or makes the color closer to) white, and the HSB solution brings the color closer to the edge in the Brigtness scale - which basically start with black and ends with the pure color...
Basically Brightness (Value) makes the color less or more closer to black, where Saturation makes it less or more closer to white...
As seen here:
So the solution to make a color actually brighter (i.e. closer to white...) will be to make it's Saturation value smaller, resulting this solution:
If you convert the RGB color to the HSL color model then you can vary the L = lightness component from L = 0.0 (black) over L = 0.5 (natural color) to L = 1.0 (white) .
UIColor
cannot handle HSL directly, but there are formula for converting RGB <-> HSL.