画像ビューにグレースケール画像を表示している場合、プログラムでその色を変更できますか? それが重要な場合、画像には透明なままにする必要がある背景の透明度があります。だから私は実際の画像部分の色だけを変更したい。
2714 次
1 に答える
0
前に簡単なカスタム 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 が表示されます。
于 2013-12-18T11:03:56.193 に答える