Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/196.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 使用PorterDuffColorFilter将位图过滤为不同的颜色_Android_Bitmap_Porter Duff_Colorfilter - Fatal编程技术网

Android 使用PorterDuffColorFilter将位图过滤为不同的颜色

Android 使用PorterDuffColorFilter将位图过滤为不同的颜色,android,bitmap,porter-duff,colorfilter,Android,Bitmap,Porter Duff,Colorfilter,我有以下图像: 现在,我想在运行时将此图像过滤为不同的颜色。例如,我希望能够生成一个绿色版本,其中下部为深绿色,左上部分为浅绿色 我该怎么做?这可能吗 我已尝试按如下方式过滤位图: private static Bitmap applyColorFilter(Bitmap source, int color) { Bitmap empty = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight()

我有以下图像:

现在,我想在运行时将此图像过滤为不同的颜色。例如,我希望能够生成一个绿色版本,其中下部为深绿色,左上部分为浅绿色

我该怎么做?这可能吗

我已尝试按如下方式过滤位图:

private static Bitmap applyColorFilter(Bitmap source, int color) {

    Bitmap empty = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight());
    Canvas c = new Canvas(empty);
    Paint p = new Paint();

    PorterDuffColorFilter pdcf = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN);
    p.setColorFilter(pcdf);
    c.drawBitmap(empty, 0, 0, p);
    source.recycle();
    return empty;
}
我试过所有的
PorterDuff.Mode
s,但没有一个真正有效。有时(例如SRC_IN),我看到圆圈完全用新颜色填充,没有任何阴影。在其他情况下,我看到一个正方形


我曾考虑过生成一个本身没有颜色的源图像,并使用alpha通道渲染其着色。然而,我不确定这是否有效。我希望生成的图像完全不透明(除了上面可以看到的外部阴影)。

我找到了一个使用
ColorMatrixColorFilter
的解决方案

// Take values from the destination color
int destA = (color >> 24);
int destR = (color >> 16) & 0xff;
int destG = (color >> 8) & 0xff;
int destB = color & 0xff;

// Give the same weight to source R,G,B, thus grasping the intensity
// -> the shading overlay
float mean = 0.33f;
ColorMatrixColorFilter cm = new ColorMatrixColorFilter(
        new float[]{
                mean,mean,mean,0,destR,
                mean,mean,mean,0,destG,
                mean,mean,mean,0,destB,
                0,0,0,1,destA }
);

Paint p = new Paint();
p.setColorFilter(cm);
...
不可避免地,这会略微改变(增亮)目标颜色,因此我会等待几天,以获得更好的解决方案。对于我的输入图像,通过将
平均值
值降低到约0.2,我可以获得更好的结果

使用
LightningColorFilter
也可能获得相同的结果