Computing the combined color of two colors (Over operator)

后端 未结 3 565
南旧
南旧 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);
    }
    
    0 讨论(0)
  • 2021-01-15 08:53

    I think what you want might be PorterDuff.Mode.Multiply

    ... used with PorterDuffColorFilter.

    EDIT: Actually maybe you want mode DST_OVER for destination color "over" source color.

    0 讨论(0)
  • 2021-01-15 08:55

    It's part of the Java Advanced Imaging API:

    http://download.java.net/media/jai/javadoc/1.1.3/jai-apidocs/javax/media/jai/operator/CompositeDescriptor.html

    http://www.oracle.com/technetwork/java/current-142188.html

    0 讨论(0)
提交回复
热议问题