开发者

Is there an easy way to blend two System.Drawing.Color values?

开发者 https://www.devze.com 2023-01-16 20:50 出处:网络
Is there an easy way 开发者_如何学Goto blend two System.Drawing.Color values? Or do I have to write my own method to take in two colors and combine them?

Is there an easy way 开发者_如何学Goto blend two System.Drawing.Color values? Or do I have to write my own method to take in two colors and combine them?

If I do, how might one go about that?


I wrote a utility method for exactly this purpose. :)

/// <summary>Blends the specified colors together.</summary>
/// <param name="color">Color to blend onto the background color.</param>
/// <param name="backColor">Color to blend the other color onto.</param>
/// <param name="amount">How much of <paramref name="color"/> to keep,
/// “on top of” <paramref name="backColor"/>.</param>
/// <returns>The blended colors.</returns>
public static Color Blend(this Color color, Color backColor, double amount)
{
    byte r = (byte) (color.R * amount + backColor.R * (1 - amount));
    byte g = (byte) (color.G * amount + backColor.G * (1 - amount));
    byte b = (byte) (color.B * amount + backColor.B * (1 - amount));
    return Color.FromRgb(r, g, b);
}


If you want to blend colours in a way that looks more natural to the human eye, you should consider working in a different colour space to RGB, such as L*a*b*, HSL, HSB.

There a great code project article on colour spaces with examples in C#.

You may like to work with L*a*b*, as it was designed to linearise the perception of color differences and should therefore produce elegant gradients.


I think its easier to blend an array of colors, in case you want to blend more then 2 Here is my function:

private Color colorBlend(List<Color> clrArr)
{   
    int r = 0;
    int g = 0;
    int b = 0;
    foreach(Color color in clrArr)
    {
        r += color.R;
        g += color.G;
        b += color.B;
    }
    r = r / clrArr.Count;
    g = g / clrArr.Count;
    b = b / clrArr.Count;
    return Color.FromArgb(r, g, b);
}

The array must be as a List of color Use :

List<Color> colorList = new List<Color>();
colorList.Add(Color.Red);
colorList.Add(Color.Blue);
picturebox.backColor = colorBlend(colorList);
0

精彩评论

暂无评论...
验证码 换一张
取 消