Skip to content Skip to sidebar Skip to footer

Android Imageview Programmatically Change Color

If I have a grayscale image displayed in an imageview, can I programmatically change its color? If it matters, the image has background transparency which would need to remain tran

Solution 1:

I write a simple custom ImageView before

below is code for reference only:

publicclassColorImageViewextendsImageView
{
private Context context;
privateboolean showColor;
private Paint mPaint;
private ColorMatrix cm;
private Bitmap mBitmap;

privatefloat[] color = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0 };
privatefloat[] normal = { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
        0, 0, 1, 0 };

publicColorImageView(Context context)
{
    super(context);
    init(context);
}

publicColorImageView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    init(context);
}

publicColorImageView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    init(context);
}

privatevoidinit(Context context)
{
    this.context = context;
    showColor = false;
    mPaint = newPaint(Paint.ANTI_ALIAS_FLAG);
    cm = newColorMatrix();
}

@OverridepublicvoidsetImageResource(int resId)
{
    // TODO Auto-generated method stubsuper.setImageResource(resId);
    mBitmap = BitmapFactory.decodeResource(context.getResources(), resId);
    invalidate();
}

@OverrideprotectedvoidonDraw(Canvas canvas)
{
    // super.onDraw(canvas);Paintpaint= mPaint;
    paint.setColorFilter(null);
    canvas.drawBitmap(mBitmap, 0, 0, paint);
    if (isShowColor())
    {
        cm.set(color);
    }
    else
    {
        cm.set(normal);
    }
    paint.setColorFilter(newColorMatrixColorFilter(cm));
    canvas.drawBitmap(mBitmap, 0, 0, paint);
}

publicvoidsetColor(int color)
{
    floatred= Color.red(color);
    floatgreen= Color.green(color);
    floatblue= Color.blue(color);
    floatalpha= Color.alpha(color);
    // 0,6,12,18this.color[0] = red / 0xFF;
    this.color[6] = green / 0xFF;
    this.color[12] = blue / 0xFF;
    this.color[18] = alpha / 0xFF;
    setShowColor(true);
}

publicbooleanisShowColor()
{
    return showColor;
}

//set true to show custom colorpublicvoidsetShowColor(boolean showColor)
{
    this.showColor = showColor;
}
}

usage:

1.put ColorImageView in xml

2.set ImageView's src in code

3.setColor(${color}) for your custom color

4.setShowColor(true) if your want to show the color.

5.ColorImageView.invalidate().(forget if this is necessary)

then the color offset ImageView will show.

Post a Comment for "Android Imageview Programmatically Change Color"