I'm trying to create a table view (custom class not UITableView) where its results have a gradient effect like in the example image below:
What I tried:
- I successfully managed to add the correct gradient as a background to every table cell but I need it to be the color of the text of each label not the background of each cell. Question. (I asked this one.)
FAILED ATEMPT:
- Creating a custom gradient image and adding it as colorWithPatternImage: to each label but since the gradient is one every cell looks the same. Question.
FAILED ATEMPT:
Last thing to try:
Suppose you have two colors, color1 and color2. A gradient can result by mixing these colors. In the picture above color1 = purple and color2 = orange. It would be easy to create a gradient effect by dividing the gradient in sections based on the number of results and then find the average color of each section and use it as the text color of each corresponding result.
For example:
5 results = 5 divisions.
- division1 = purple
- division2 = less purple, more orange
- division3 = equal purple, equal orange
- division4 = least purple, most orange
- division5 = orange
The result is not as detailed because each text is a solid color but it is equally impressive when the text is small:
The problem is, for two colors like these:
Purple: 128.0, 0.0, 255.0
Orange: 255.0, 128.0, 0.0
How do you divide it in 5 sections and find the average of each section?
I could do this using the eyedropper tool in pixelmator but only if I knew the fixed number of results, won't work with 6 results.
I can't approach it with math, I don't know where to begin.
Any ideas?
You can use math on the rgb values of the colors.
To get the rgb values, you can use the
getRed:green:blue:alpha
method onUIColor
. Then all you have to do is average the colors together based on how many sections you need.Here is a function that should return an array of colors based on a start and end color, and how many divisions you need.
Solution
Your question is tagged as
Objective-C
, but it should be easy enough to convert the Swift code above to Objective-C since you would use the sameUIColor
API.Here is some code to test the above function (perfect for a Swift playground).
Testing Code
Test Result
It also works for any number of sections and different colors!