Imageview 将滤色器设置为渐变

Imageview set color filter to gradient(Imageview 将滤色器设置为渐变)

本文介绍了Imageview 将滤色器设置为渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张白色图像,我想用渐变着色.我不想生成一堆图像,每个图像都有特定的渐变色,我想在代码(不是 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.

编辑:这是我的图片:

这就是我想要的:

这就是我得到的:

推荐答案

你必须得到 ImageViewBitmap 并重绘相同的 Bitmap着色器

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 宽度 = 0 和 PorterDuffXfermode.这里有一张好图了解 PorterDuffXfermode:

UPDATE 3 I changed: colors of gradient, LinearGradient width = 0 and PorterDuffXfermode. Here a good picture to understand PorterDuffXfermode:

这篇关于Imageview 将滤色器设置为渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Imageview 将滤色器设置为渐变

基础教程推荐