javaandroidmatrixbitmapcolormatrix

Change Bitmap Colour with function


I need a function that will take a bitmap and return the bitmap with a changed colour. It needs to be fast and simple.

It's purpose is to change the colour, also it's a png with alphas.

I've had a look online but I can't use canvas or anything external. The function resides in an external object (Don't ask..)

Here is what I've had a go at so far (not working). I know I'm really close, just a matter fo sorting out the color matrix and getting alpha to work.

public Bitmap changeBitmapColor(Bitmap sourceBitmap, int deg)
{   
    int width, height;
    height = sourceBitmap.getHeight();
    width = sourceBitmap.getWidth();    

    Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

    Canvas c = new Canvas(bmpGrayscale);
    Paint paint = new Paint();

    //figure out color matricies.
    ColorMatrix cm = new ColorMatrix();

    //cm.setSaturation(0);

    cm.set(new float[] 
    {
            0, 0, 0, 0, 0,
            0, 1, 0, 0, 0,
            0, 0, 255, 0, 0,
            0, 0, 0, 1, 0,
            0, 0, 0, 0, 1
         }); 


    ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
    paint.setColorFilter(f);

    c.drawBitmap(sourceBitmap, 0, 0, paint);

    return bmpGrayscale;
}

Any help would be great!

------- FIXED --------

I've fixed this by changing the colour matrix, now the bitmap will change colour & not show the alpha values.

First thing is the matrix:

    cm.set(new float[] 
    {
            0, 0, 0, 0, 0,
            0, 1, 0, 0, 0,
            0, 0, 140, 0, 0,
            0, 0, 0, 1, 0,
            0, 0, 0, 0, 1
    }); 

Second thing I had to change was this line of code:

Bitmap newBM = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

Good luck readers!


Solution

  • ------- FIXED --------

    I've fixed this by changing the colour matrix, now the bitmap will change colour & not show the alpha values.

    First thing is the matrix:

    cm.set(new float[] 
    {
            0, 0, 0, 0, 0,
            0, 1, 0, 0, 0,
            0, 0, 140, 0, 0,
            0, 0, 0, 1, 0,
            0, 0, 0, 0, 1
    }); 
    

    Second thing I had to change was this line of code:

    Bitmap newBM = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    Good luck readers!