WPF Color interpolation

后端 未结 5 1197
离开以前
离开以前 2021-01-15 14:43

I am trying to paint a WPF control\'s background based on a palette where each color has been assigned with values (e.g. Red = 0, DarkGreen = 10, Green = 20,LightGreen =30)

5条回答
  •  迷失自我
    2021-01-15 14:55

    Using the LinearGradientBrush sounds like it would have a bit of an overhead. No knowledge though. A color interpolation function isn't that hard to write though.

    I'm assuming your palettes have values that are divisible by 10 for simplicity.

    public static Color GetColor(int value)
    {
        int startIndex = (value/10)*10;
        int endIndex = startIndex + 10;
    
        Color startColor = Palette[startIndex];
        Color endColor = Palette[endIndex];
    
        float weight = (value - startIndex)/(float)(endIndex - startIndex);
    
        return Color.FromArgb(
            (int)Math.Round(startColor.R * (1 - weight) + endColor.R * weight),
            (int)Math.Round(startColor.G * (1 - weight) + endColor.G * weight),
            (int)Math.Round(startColor.B * (1 - weight) + endColor.B * weight));
    
    }
    

    If the defined colors are not divisible by 10 the logic to find the start and end colors will be a bit more complex.

提交回复
热议问题