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 将滤色器设置为渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)