WPF Color interpolation

后端 未结 5 1202
离开以前
离开以前 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 15:17

    I'm not sure if this was the case back then but in .NET 4.0 getting a color from a LinearGradientBrush can be done.

    private Color GetColor(double ratio)
    {
        if (ratio < 0) ratio = 0;
        else if (ratio > 1) ratio = 1;
    
        //Find gradient stops that surround the input value
        GradientStop gs0 = ColorScale.GradientStops.Where(n => n.Offset <= ratio).OrderBy(n => n.Offset).Last();
        GradientStop gs1 = ColorScale.GradientStops.Where(n => n.Offset >= ratio).OrderBy(n => n.Offset).First();
    
        float y = 0f;
        if (gs0.Offset != gs1.Offset)
        {
            y = (float)((ratio - gs0.Offset) / (gs1.Offset - gs0.Offset));
        }
    
        //Interpolate color channels
        Color cx = new Color();
        if (ColorScale.ColorInterpolationMode == ColorInterpolationMode.ScRgbLinearInterpolation)
        {
            float aVal = (gs1.Color.ScA - gs0.Color.ScA) * y + gs0.Color.ScA;
            float rVal = (gs1.Color.ScR - gs0.Color.ScR) * y + gs0.Color.ScR;
            float gVal = (gs1.Color.ScG - gs0.Color.ScG) * y + gs0.Color.ScG;
            float bVal = (gs1.Color.ScB - gs0.Color.ScB) * y + gs0.Color.ScB;
            cx = Color.FromScRgb(aVal, rVal, gVal, bVal);
        }
        else
        {
            byte aVal = (byte)((gs1.Color.A - gs0.Color.A) * y + gs0.Color.A);
            byte rVal = (byte)((gs1.Color.R - gs0.Color.R) * y + gs0.Color.R);
            byte gVal = (byte)((gs1.Color.G - gs0.Color.G) * y + gs0.Color.G);
            byte bVal = (byte)((gs1.Color.B - gs0.Color.B) * y + gs0.Color.B);
            cx = Color.FromArgb(aVal, rVal, gVal, bVal);
        }
        return cx;
    }
    

    This would work with a brush configured as follows (for example):

    var brush = new LinearGradientBrush();
    brush.StartPoint = new Point(0, 0);
    brush.EndPoint = new Point(1, 0);
    
    //Set brush colors
    brush.GradientStops.Add(new GradientStop() { Color = Color.FromRgb(102, 40, 0), Offset = 0 });
    brush.GradientStops.Add(new GradientStop() { Color = Color.FromRgb(254, 167, 80), Offset = 0.25 });
    brush.GradientStops.Add(new GradientStop() { Color = Color.FromRgb(0, 153, 51), Offset = 0.5 });
    brush.GradientStops.Add(new GradientStop() { Color = Color.FromRgb(232, 165, 255), Offset = 0.75 });
    brush.GradientStops.Add(new GradientStop() { Color = Color.FromRgb(66, 0, 89), Offset = 1 });
    

    Source: http://dotupdate.wordpress.com/2008/01/28/find-the-color-of-a-point-in-a-lineargradientbrush/

提交回复
热议问题