gpt4 book ai didi

java - 从一组颜色中获取平均值

转载 作者:行者123 更新时间:2023-11-30 08:08:57 25 4
gpt4 key购买 nike

我使用了各种颜色实用程序来混合颜色,但由于顺序困惑,它产生了不正确的值。我环顾四周,只发现了单一颜色或两种颜色混合。

因此,我将颜色放入一个数组中,目前我正在尝试弄清楚如何混合它们,但现在我被卡住了。

我的尝试:

Array<Color> colorsArray;
for(Color eachColor : colors)
colorsArray.add(new Color(
eachColor.r, eachColor.g, eachColor.b,
strength //<<Varies.
);
));

/We have an array of play colors and there strengths, process them into an average.
float totalRed = 0f, totalBlue = 0f, totalGreen = 0f;
for(ColorStorage colorStorage : colorVectorsWithInfectionStrength)
{
totalRed += (colorStorage.getRed() * colorStorage.getAlpha());
totalBlue += (colorStorage.getBlue() * colorStorage.getAlpha());
totalGreen += (colorStorage.getGreen() * colorStorage.getAlpha());
}

/* Makes dark colors. HMM.
totalRed /= colorVectorsWithInfectionStrength.size;
totalBlue /= colorVectorsWithInfectionStrength.size;
totalGreen /= colorVectorsWithInfectionStrength.size;
*/

ColorStorage averageColor = new ColorStorage(totalRed, totalBlue, totalGreen);

//varying var goes from 0-1 depending on the max strength.
endColor = ColorUtils.blend(averageColor, endColor, varyingVar);

混合函数:

public static ColorStorage blend(ColorStorage color1, ColorStorage color2, double ratio)
{
float r = (float) ratio;
float ir = (float) 1.0 - r;

float rgb1[] = color1.getColorComponents();
float rgb2[] = color2.getColorComponents();

return new ColorStorage (
rgb1[0] * r + rgb2[0] * ir,
rgb1[1] * r + rgb2[1] * ir,
rgb1[2] * r + rgb2[2] * ir
);
}

编辑这里的颜色对象是自定义的,它总是为 RGBA 返回 0-1f。 (每个值)

最佳答案

您尝试除以数组大小,但生成的颜色太暗。这是因为您将每个分量乘以 alpha 值(而不是 1,就像没有 alpha channel 那样)。如果你想正确地标准化颜色,你需要除以 alpha 的总和。

float totalAlpha = 0;
for(ColorStorage colorStorage : colorVectorsWithInfectionStrength)
{
totalRed += (colorStorage.getRed() * colorStorage.getAlpha());
totalBlue += (colorStorage.getBlue() * colorStorage.getAlpha());
totalGreen += (colorStorage.getGreen() * colorStorage.getAlpha());
totalAlpha += colorStorage.getAlpha();
}

totalRed /= totalAlpha;
totalBlue /= totalAlpha;
totalGreen /= totalAlpha;

这应该会给你正确的比例。

请注意,它也不会为您提供准确的混合,因为 RGB 色彩空间不是线性的。但它足够接近休闲使用。

关于java - 从一组颜色中获取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32811876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com