Search code examples
javainterpolationargb

How to do ARGB color interpolation without separating components?


After trying and failing to figure this out myself, I have scavenged some code which should combine two colors (integers) by a specified fraction from another thread, but I am just simply not crafty enough to get it working with ARGB integers. Does anyone know how to convert this function from combining RGB to combining ARGB?

public static int mixColors(int a, int b, float fractionB){ 
   int mask1 = 0xff00ff; 
   int mask2 = 0x00ff00; 
    
   int f2 = (int)(256 * fractionB);
   int f1 = 256 - f2;
   
   return   ((((( a & mask1 ) * f1 ) + ( ( b & mask1 ) * f2 )) >>> 8 ) & mask1 ) 
          | ((((( a & mask2 ) * f1 ) + ( ( b & mask2 ) * f2 )) >>> 8 ) & mask2 );
}

I have tried setting the masks to mask1 = 0x00ff00ff; mask2 = 0xff00ff00; but the function still only outputs a 3 byte number.


Solution

  • "...since using int the 4th byte is lost - you can use long in the calculation (mask and factors) to avoid that" - user16320675

    Thank you! I should have thought of that, but I guess that's what they all say. Here are the updated functions for 32bit integer ARGB color values:

    public static int mixColors(int a, int b){
        long mask1 = 0x00ff00ffL;
        long mask2 = 0xff00ff00L;
    
        return (int)((((((a & mask1) + (b & mask1)) * 128) >> 8) & mask1) 
                   | (((((a & mask2) + (b & mask2)) * 128) >> 8) & mask2));
    }
    
    public static int mixColors(int a, int b, float fractionB){
        long mask1 = 0x00ff00ffL;
        long mask2 = 0xff00ff00L;
    
        short f2 = (short)(256 * fractionB),
              f1 = (short)(256 - f2);
              
        return (int)((((((a & mask1) * f1) + ((b & mask1) * f2)) >> 8) & mask1) 
                   | (((((a & mask2) * f1) + ((b & mask2) * f2)) >> 8) & mask2));
    }