我想更改imageview中存在的图像颜色。我从Bitmap对象的imageview获取了图像,并在其上应用了colormatrix。 问题是,一旦我改变了图像的颜色,它就不会改变bt覆盖以前的颜色, 我想要的是,当我更改颜色时,应删除之前的图像颜色,并应用我选择的任何特定颜色。
我正在使用以下代码来执行此操作...
void setImageColor(RGBColor rgbcolor,ImageView view)//,Bitmap sourceBitmap)
{
view.setDrawingCacheEnabled(true);
Bitmap sourceBitmap = view.getDrawingCache();
if(sourceBitmap!=null)
{
float R = (float)rgbcolor.getR();
float G = (float)rgbcolor.getG();
float B = (float)rgbcolor.getB();
Log.v("R:G:B",R+":"+G+":"+B);
float[] colorTransform =
{ R/255f, 0, 0, 0, 0, // R color
0, G/255f, 0, 0, 0, // G color
0, 0, B/255f, 0, 0, // B color
0, 0, 0, 1f, 0f
};
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0f); //Remove Colour
colorMatrix.set(colorTransform);
ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
Paint paint = new Paint();
paint.setColorFilter(colorFilter);
Bitmap mutableBitmap = sourceBitmap.copy(Bitmap.Config.ARGB_8888, true);
view.setImageBitmap(mutableBitmap);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawBitmap(mutableBitmap, 0, 0, paint);
}
else
return;
}
答案 0 :(得分:1)
声明一个静态sourceBitmap
并且只执行一次:Bitmap sourceBitmap = view.getDrawingCache();
让我们在您的活动的onResume()
中说(或者当您从ImageView更改图像时)。
你的功能应该是:
void setImageColor(RGBColor rgbcolor, ImageView view, Bitmap sourceBitmap) {
if (sourceBitmap == null) return;
float r = (float) rgbcolor.getR(),
g = (float) rgbcolor.getG(),
b = (float) rgbcolor.getB();
Log.v("R:G:B", r + ":" + g + ":" + b);
float[] colorTransform =
{
r/255, 0 , 0 , 0, 0, // R color
0 , g/255, 0 , 0, 0, // G color
0 , 0 , b/255, 0, 0, // B color
0 , 0 , 0 , 1, 0
};
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0f); // Remove colour
colorMatrix.set(colorTransform);
ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
Paint paint = new Paint();
paint.setColorFilter(colorFilter);
Bitmap mutableBitmap = sourceBitmap.copy(Bitmap.Config.ARGB_8888, true);
view.setImageBitmap(mutableBitmap);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawBitmap(mutableBitmap, 0, 0, paint);
}
这样您就可以保留未经改动的图像,并将过滤器应用于原始图像。