3

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?

pavel
  • 26,538
  • 10
  • 45
  • 61
halpsb
  • 1,106
  • 2
  • 18
  • 28
  • Why can't you just average each of the three components separately? – Dawood ibn Kareem Jul 23 '14 at 12:21
  • You should specify what "median" means. But I think that it is simply the average value of each of the RGB components, right? – Seelenvirtuose Jul 23 '14 at 12:22
  • A color can be split in (R,G,B) or (H,S,V) and then you can take the median of the single component aspects. Instead of a simple average one could do a "gamma" correction, but is not necessary here. `Color.getRed()/Green/Blue, new Color(r, g, b)`. – Joop Eggen Jul 23 '14 at 12:23

2 Answers2

5

you can try this perhaps:

new ArgbEvaluator().evaluate(0.5, 0xffffff, 0x000000);

more info: http://developer.android.com/reference/android/animation/ArgbEvaluator.html :

erik
  • 4,946
  • 13
  • 70
  • 120
2

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());

     }
brain
  • 5,496
  • 1
  • 26
  • 29