【问题标题】:Android imageview programmatically change colorAndroid imageview以编程方式更改颜色
【发布时间】:2013-03-24 13:37:31
【问题描述】:

如果我在图像视图中显示灰度图像,我可以通过编程方式更改其颜色吗?如果重要,图像具有背景透明度,需要保持透明。所以我只想改变实际图像部分的颜色。

【问题讨论】:

  • 这很有趣。我希望我可以使用 myImageView.setColor(Color.parseColor("#ffff0000")) 之类的东西,类似于我在应用程序中更改字体颜色的方式。这样我就可以确定字体和图标的颜色/透明度相同。但我也许可以使这个建议奏效。

标签: android imageview


【解决方案1】:

我之前写了一个简单的自定义ImageView

以下代码仅供参考:

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;
}
}

用法:

1.将ColorImageView放入xml中

2.在代码中设置ImageView的src

3.setColor(${color}) 为您的自定义颜色

4.setShowColor(true) 如果你想显示颜色。

5.ColorImageView.invalidate().(必要时忘记)

然后ImageView会显示颜色偏移。

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 2015-04-02
    • 1970-01-01
    • 2015-12-06
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    相关资源
    最近更新 更多