I have a white image that I'd like to color with a gradient. Instead of generating a bunch of images each colored with a specific gradient, I'd like to do this in code (not xml).
To change an image's color, I use
imageView.setColorFilter(Color.GREEN);
And this works fine. But how can I apply a gradient color instead of a solid color? LinearGradient
doesn't help, because setColorFilter can't be applied to Shader
objects.
EDIT: This is the image I have:
This is what I want:
And this is what I'm getting:
You have to get Bitmap
of your ImageView
and redraw same Bitmap
with Shader
public void clickButton(View v){
Bitmap myBitmap = ((BitmapDrawable)myImageView.getDrawable()).getBitmap();
Bitmap newBitmap = addGradient(myBitmap);
myImageView.setImageDrawable(new BitmapDrawable(getResources(), newBitmap));
}
public Bitmap addGradient(Bitmap originalBitmap) {
int width = originalBitmap.getWidth();
int height = originalBitmap.getHeight();
Bitmap updatedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(updatedBitmap);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, 0, 0, height, 0xFFF0D252, 0xFFF07305, Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawRect(0, 0, width, height, paint);
return updatedBitmap;
}
UPDATE 3 I changed: colors of gradient, LinearGradient width = 0 and PorterDuffXfermode. Here a good picture to understand PorterDuffXfermode: