Reputation: 3887
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.
Upvotes: 7
Views: 4784
Reputation: 1336
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;
}
Upvotes: 11
Reputation: 330
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.
Upvotes: 3