Android imageview programmatically change color

被刻印的时光 ゝ 提交于 2019-12-11 18:59:57

问题


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 transparent. So I only want to change the color of the actual image part.


回答1:


I write a simple custom ImageView before

below is code for reference only:

public class ColorImageView extends ImageView
{
private Context context;
private boolean showColor;
private Paint mPaint;
private ColorMatrix cm;
private Bitmap mBitmap;

private float[] color = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0 };
private float[] normal = { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
        0, 0, 1, 0 };

public ColorImageView(Context context)
{
    super(context);
    init(context);
}

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

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

private void init(Context context)
{
    this.context = context;
    showColor = false;
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    cm = new ColorMatrix();
}

@Override
public void setImageResource(int resId)
{
    // TODO Auto-generated method stub
    super.setImageResource(resId);
    mBitmap = BitmapFactory.decodeResource(context.getResources(), resId);
    invalidate();
}

@Override
protected void onDraw(Canvas canvas)
{
    // super.onDraw(canvas);
    Paint paint = mPaint;
    paint.setColorFilter(null);
    canvas.drawBitmap(mBitmap, 0, 0, paint);
    if (isShowColor())
    {
        cm.set(color);
    }
    else
    {
        cm.set(normal);
    }
    paint.setColorFilter(new ColorMatrixColorFilter(cm));
    canvas.drawBitmap(mBitmap, 0, 0, paint);
}

public void setColor(int color)
{
    float red = Color.red(color);
    float green = Color.green(color);
    float blue = Color.blue(color);
    float alpha = Color.alpha(color);
    // 0,6,12,18
    this.color[0] = red / 0xFF;
    this.color[6] = green / 0xFF;
    this.color[12] = blue / 0xFF;
    this.color[18] = alpha / 0xFF;
    setShowColor(true);
}

public boolean isShowColor()
{
    return showColor;
}

//set true to show custom color
public void setShowColor(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.



来源:https://stackoverflow.com/questions/15599108/android-imageview-programmatically-change-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!