get Colored Bitmap - Android Graphics

Android examples for Graphics:Bitmap Color

Description

get Colored Bitmap

Demo Code

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;

public class Main {
  public static Bitmap getColoredBitmap(Context context, Bitmap bitmap, int color) {
    int alpha = Color.alpha(color);
    int red = Color.red(color);
    int green = Color.green(color);
    int blue = Color.blue(color);

    int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
    bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
    for (int i = 0; i < pixels.length; i++) {
      int pixel = pixels[i];
      int pixelAlpha = Color.alpha(pixel);
      if (pixelAlpha != 0)
        pixels[i] = Color.argb((int) (pixelAlpha * alpha / 256f), red, green, blue);
    }/*w  w w  .j  a  va 2 s  .  com*/

    Bitmap coloredBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
    coloredBitmap.setPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
    return coloredBitmap;
  }

  public static Bitmap getColoredBitmap(Context context, int drawableRes, int color) {
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), drawableRes);
    return getColoredBitmap(context, bitmap, color);
  }
}

Related Tutorials