Reputation: 11
I want to change the color of image that exist in imageview. i got the image from imageview in Bitmap object and applied colormatrix on it. The problem is that , once i change the color of image, it doesn't change bt override the previous color, I want that , when i change the color, the previous color of image should be removed and any specific color that i choose is applied.
i am using the following code to do that...
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;
}
Upvotes: 1
Views: 2613
Reputation: 347
Declare a static sourceBitmap
and do this only once: Bitmap sourceBitmap = view.getDrawingCache();
let's say in onResume()
of your activity (or when you change the image from ImageView).
And your function should be:
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);
}
This way you will hold the unaltered image and apply the filters on the original.
Upvotes: 1