Computing the combined color of two colors (Over operator)

后端 未结 3 564
南旧
南旧 2021-01-15 08:28

This is for an Android application. Let\'s say that I have two colors with alpha

int color1 = 0x12345678  // aarrggbb
int color2 = 0x87654321
3条回答
  •  悲哀的现实
    2021-01-15 08:51

    I ended up implementing it. A direct rewrite of the Wikipedia formula. Any issue with this implementation?

    // a2 over a1
    private static int compositeAlpha(int a1, int a2) {
        return 255 - ((255 - a2) * (255 - a1)) / 255;
    }
    
    
    // For a single R/G/B component. a = precomputed compositeAlpha(a1, a2)
    private static int compositeColorComponent(int c1, int a1, int c2, int a2, int a) {
        // Handle the singular case of both layers fully transparent.
        if (a == 0) {
            return 0x00;
        }
        return (((255 * c2 * a2) + (c1 * a1 * (255 - a2))) / a) / 255;
    }
    
    // argb2 over argb1. No range checking.
    public static int compositeColor(int argb1, int argb2) {
        final int a1 = Color.alpha(argb1);
        final int a2 = Color.alpha(argb2);
    
        final int a = compositeAlpha(a1, a2);
    
        final int r = compositeColorComponent(Color.red(argb1), a1,   
                Color.red(argb2), a2, a);
        final int g = compositeColorComponent(Color.green(argb1), a1, 
                Color.green(argb2), a2, a);
        final int b = compositeColorComponent(Color.blue(argb1), a1, 
            Color.blue(argb2), a2, a);
    
        return Color.argb(a, r, g, b);
    }
    

提交回复
热议问题