0
如果我在圖像視圖中顯示灰度圖像,是否可以編程方式更改其顏色?如果它很重要,圖像具有需要保持透明的背景透明度。所以我只想改變實際圖像部分的顏色。android imageview以編程方式更改顏色
如果我在圖像視圖中顯示灰度圖像,是否可以編程方式更改其顏色?如果它很重要,圖像具有需要保持透明的背景透明度。所以我只想改變實際圖像部分的顏色。android imageview以編程方式更改顏色
我寫了一個簡單的自定義的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;
}
}
用法:在XML
1.put ColorImageView
2.設置的ImageView SRC代碼
3.setColor($ {color})爲您的自定義c olor
4.setShowColor(true)如果你想顯示顏色。
5.ColorImageView.invalidate()。(忘了,如果這是必要的)
那麼顏色偏移的ImageView就會顯示。
http://stackoverflow.com/a/7917978/1531054 – 2013-03-24 13:49:19
這很有趣。我希望我可以使用像myImageView.setColor(Color.parseColor(「#ffff0000」)),類似於我更改我的應用程序中的字體顏色。這樣我可以確定字體和圖標是相同的顏色/透明度。但我可能能夠提出這個建議。 – MrGibbage 2013-03-24 14:31:36