Android: The easiest way to change the color of a png file

I am writing a game in which there is a main sprite (balloon). Currently, I have two different PNGs of the color ball that I created, I need to create more (maybe 5 more or so) and do not want to have 7 different png files. (this would be 20 additional files, since I have 4 different sizes for scaling). I would rather stick with 1 - the ones that I have at the moment are yellow and red (almost solid, but not quite - they have details on them).

Question. Is there an easy way to change the color of my existing PNG files? I have seen people mention setColor and setColorFilter , but I cannot figure out how to use them. Will they also work with PNG files that already have color or work only with white PNG files (I don’t think my PNG can be just white)?

Thanks, any help would be appreciated.

+7
source share
2 answers

You can try to define a custom ColorMatrix with random rgb 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); 

Hope this helps.

+3
source

You can use only black PNG file to create different color shades.

The code below sets the color using some kind of fancy blending blend mode.

 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; } 
+11
source

All Articles