Imageview将滤镜设置为渐变 [英] Imageview set color filter to gradient
问题描述
我有一张白色图片,我想用渐变色。我不想生成一堆每个用特定渐变着色的图像,而是想在代码(而不是xml)中执行此操作。
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);
这很好用。但是,如何应用渐变色而不是纯色? LinearGradient
没有帮助,因为setColorFilter无法应用于 Shader
对象。
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.
编辑:这是我的图片:
这就是我想要的:
这就是我得到的:
推荐答案
你必须得到你的位图
code> ImageView 并使用 Shader
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;
}
更新3
我更改了:渐变颜色,LinearGradient width = 0和PorterDuffXfermode。
这是一张了解PorterDuffXfermode的好照片:
UPDATE 3 I changed: colors of gradient, LinearGradient width = 0 and PorterDuffXfermode. Here a good picture to understand PorterDuffXfermode:
这篇关于Imageview将滤镜设置为渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!