Search code examples
javaandroidcolorsgradientmedian

Get median color between two colors


I have 2 string representations of colors (ex: "#FFFFFF" and "#000000") and I am looking for a way to get the median color of these two colors programmatically. The color I call "median" would be the color that meets these two in the center.

I need this in order to draw a gradient in 2 steps :

  • 1 gradient from the first color to the median
  • 1 gradient from the median to the second color

So that it looks like 1 gradient from the first to the second color, which I cannot do.

How can I achieve that?


Solution

  • I would process each RGB component separately. You can parse the hex into a number using Long.valueOf(). Average your two values (rounding as needed) and then going to back to hex using Long.toString() padding out to two digits.

    Some example code that I havn't tested:

         String colour1 = "#FFFFFF";
         String colour2 = "#000000";
    
         StringBuilder result = new StringBuilder("#");
         for (int i=0;i<3;i++) {
             String h1 = colour1.substring(i*2+1, 3+(i*2));
             String h2 = colour2.substring(i*2+1, 3+(i*2));
    
             long l1 = Long.parseLong(h1, 16);
             long l2 = Long.parseLong(h2, 16);
    
             long mid = (l1 + l2) / 2; //truncating not rounding
    
             String midStr = Long.toString(mid, 16);
             if (midStr.length() == 1) {
                 result.append("0");
             }
             result.append(midStr.toUpperCase());
    
         }