Almost two years, I experimented with using the dominant color of a favicon to give a small icon a colorful background. And over the past week, I wrote some patches to incorporate this design into Firefox for Android!
The simple algorithm I wrote long ago was done in JS with canvas, but to use this in our native Android UI, it’s simplest to just do it in Java. Luckily, we already had a dominant color utility method in the tree, but creating a background and border with different saturation levels was trickier than I thought it would be. To solve this problem, I gave the ImageView a background drawable with a solid white interior and a gray border, then applied a transparent version of the dominant color as a color filter. This worked pretty well once I figured out which PorterDuff mode to use, but it made me appreciate the simplicity of CSS.
When testing with various icons, I found that our dominant color algorithm could use some improvement. Our Java algorithm is different than the one I experimented with in JS mainly because it uses the HSV color model as opposed to RGB. Instead of counting every distinct color, we split the range of hues into different bins and find the bin that holds the most colors. For the winning bin, we compute the average H, S, and V values within that bin, and return that as the dominant color. To make sure we only return colorful colors, we ignore transparent pixels, as well as pixels that are close enough to black or white. This simple algorithm may not be perfect, but it works pretty well for us, especially for small favicons.
As an interesting bit of history, after I blogged about my dominant color experiment, Mardak wrote an add-on that used an improved version of my JS snippet. At the time, Wes saw this add-on and incorporated the code into XUL Fennec to create icons for homescreen shortcuts. During the Fennec Native rewrite, Wes reimplemented this feature in Java, and that’s the code I found myself in last week. And for those interested in a more robust solution implemented in JS, there’s actually a toolkit service that does this now.