Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Easiest way to change the colour of a png file

I'm writing a game which has a basic sprite (a balloon) - currently I have 2 different color balloon PNG files which I have created, I need to create more (probably another 5 or so) and don't want to have like 7 different png files. (that would be 20 extra files as I have 4 different sizes for scaling purposes) I would rather stick to 1 - the ones I have at the moment are yellow and red (almost solid, but not quite - they have details on them).

Question - is there a simple way to alter the colour of my existing PNG files? I've seen people mention setColor and setColorFilter but I can't work out how to use these. Also will these even work on PNG files that already have a colour or do they only work on White PNG files (I don't think my PNG's can realistically be just white)?

Thank you all any help would be appreciated.

like image 360
Zippy Avatar asked Dec 30 '12 19:12

Zippy


2 Answers

You can use just black baloon png file to create different color baloons.

The below code sets the color using some fancy blending mode trickery.

protected BitmapDrawable setIconColor(int color) {
    if (color == 0) {
        color = 0xffffffff;
    }

    final Resources res = getResources();
    Drawable maskDrawable = res.getDrawable(R.drawable.actionbar_icon_mask);
    if (!(maskDrawable instanceof BitmapDrawable)) {
        return;
    }

    Bitmap maskBitmap = ((BitmapDrawable) maskDrawable).getBitmap();
    final int width = maskBitmap.getWidth();
    final int height = maskBitmap.getHeight();

    Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(outBitmap);
    canvas.drawBitmap(maskBitmap, 0, 0, null);

    Paint maskedPaint = new Paint();
    maskedPaint.setColor(color);
    maskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));

    canvas.drawRect(0, 0, width, height, maskedPaint);

    BitmapDrawable outDrawable = new BitmapDrawable(res, outBitmap);
    return outDrawable;
}
like image 87
Nitin Sethi Avatar answered Sep 20 '22 23:09

Nitin Sethi


You can try to define a custom ColorMatrix with random r g b values:

Random rand = new Random();
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);

ColorMatrix cm = new ColorMatrix();
cm.set(new float[] {
                   1, 0, 0, 0, r,
                   0, 1, 0, 0, g,
                   0, 0, 1, 0, b,
                   0, 0, 0, 1, 0 }); // last line is antialias
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(myBitmap, toX, toY, paint);

I hope it helps.

like image 43
peekler Avatar answered Sep 18 '22 23:09

peekler