如何在代码中实现鲜艳的浅色混合?

时间:2015-08-09 21:07:34

标签: colors color-theory blending

我正在尝试在代码中实现鲜艳的浅色混合(我猜c#现在)。我发现有两页说明了如何做,但我不理解他们的符号。

http://www.deepskycolors.com/archive/2010/04/21/formulas-for-Photoshop-blending-modes.html https://en.wikipedia.org/wiki/Blend_modes

有谁知道如何将其转换为代码?从我的结尾,我有两个带有r,g,b值的Color对象。任何人都可以显示算法,但使用r,g,b值吗?

由于

以下是我的非工作实施:

using System;
using System.Drawing;

namespace CardMaker
{
    class VividLight : ColorFilter
    {
        public override Color GetFilteredColor(Color p1, Color p2)
        {
            int newR = Math.Max(0, Math.Min(255, Convert.ToInt32(GetColor(p1.R, p2.R))));
            int newG = Math.Max(0, Math.Min(255, Convert.ToInt32(GetColor(p1.G, p2.G))));
            int newB = Math.Max(0, Math.Min(255, Convert.ToInt32(GetColor(p1.B, p2.B))));

            return Color.FromArgb(newR, newG, newB);
        }

        private static double GetColor(int c1, int c2)
        {
            if (c2 > 128)
            {
                return 256 - ((256 - c1) / (512 * (c2 - 128)));
            }
            else
            {
                return c1 / (256 - 512 * c2);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

公式是[0,1]中的浮点数,并已将其转换为[0,255]。您还相应地缩放了公式中使用的常量。

然而,其中一些常数具有附加作用,其中一些具有乘法作用。你应该在这些情况之间做些什么不同。将要添加的数字可以按照您的方式进行缩放,但是不会增加的数字(结果将已经正确缩放,因为其他被乘数(其中一个颜色值)已经缩放)。这与在定点算术中实现乘法时面临的问题直接类比。

在这里,无论你说过512,你应该说2。

作为旁注,您应该注意整数和浮点除法之间可能的速度/精度权衡。你的方法说它返回了一个double,但是return语句中的表达式求值为int(并使用整数除法,向下舍入)。然后,编译器将该结果扩展为评估后的两倍。通过使用浮点除法可能会使结果更精确(和更慢)(为此,使用常数2.0而不是2) - 尽管因为在除法之后没有发生任何乘法,所以可能没什么大不了的。尝试两种方式。

    private static double GetColor(int c1, int c2)
    {
        if (c2 > 128)
        {
            return 256 - ((256 - c1) / (2 * (c2 - 128)));
        }
        else
        {
            return c1 / (256 - 2 * c2);
        }
    }