0

I have a method that take a Bitmap and a color, and converts all the pixels on the Bitmap to that color, while keeping the original's alpha values. In addition, the method is written so that as the color passed in gets darker, the Bitmap is made more transparent rather than darker. If the color passed in is completely black, then the Bitmap should be made entirely transparent instead of black.

public static Bitmap colorImage(Bitmap img, int red, int green, int blue) {
    int max = blue;
    if (red >= green && red >= blue)
        max = red;
    else if (green >= red && green >= blue)
        max = green;
    double scale = 255.0 / max;
    red = (int)(scale * red);
    green = (int)(scale * green);
    blue = (int)(scale * blue);
    Bitmap resultBitmap = img.copy(Bitmap.Config.ARGB_8888, true);
    float[] colorTransform = {
            0, 0, 0, 0, red, 
            0, 0, 0, 0, green,
            0, 0, 0, 0, blue, 
            0, 0, 0, (float) (1f / scale), 0};

    ColorMatrix colorMatrix = new ColorMatrix(colorTransform);
    ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);

    Paint paint = new Paint();
    paint.setColorFilter(colorFilter);   

    Canvas canvas = new Canvas(resultBitmap);
    canvas.drawBitmap(resultBitmap, 0, 0, paint);
    return resultBitmap;

}

There is an issue with making the Bitmap transparent.

If I set the color matrix so that it is as follows,

float[] colorTransform = {
            0, 0, 0, 0, red, 
            0, 0, 0, 0, green,
            0, 0, 0, 0, blue, 
            0, 0, 0, 0, 0};

the entire Bitmap should be made completely transparent. However, this only works correctly if the original Bitmap has no transparency at all. If the Bitmap has only alpha values of 255 for all of its pixels, then the result is completely transparent. However, if the Bitmap has any pixel with an alpha value of less than 255, the final image will not be transparent, but will have the same alpha values as the original.

Can anybody tell why?

Thanks in advance.

1 Answer 1

0

Bitmaps by default have black backgrounds. Setting the Bitmap's background to transparent resolves the issue.

This can be done by adding resultBitmap.eraseColor(Color.argb(0, 0, 0, 0)); after resultBitmap is declared, changing canvas.drawBitmap(resultBitmap, 0, 0, paint); to canvas.drawBitmap(img, 0, 0, paint);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.