Search code examples
wpfxamllineargradientbrush

How to read the color from an offset of a XAML LinearGradientBrush?


Given a LinearGradientBrush defined as follows:

        <LinearGradientBrush x:Key="RedYellowGradient">
            <GradientStop Color="Blue" Offset="0.01" />
            <GradientStop Color="Purple" Offset="0.25"/>
            <GradientStop Color="Red" Offset="0.5"/>
            <GradientStop Color="Orange" Offset="0.75"/>
            <GradientStop Color="Yellow" Offset="1.0"/>
        </LinearGradientBrush>

What is required to take that definition and determine the color represented by a specific offset, such as 0.13 or 0.82 without rendering anything visible?

This would take the form of a function with a prototype something like this:

Function GetColorFromBrushOffset(br as LinearGradientBrush, offset as Single) as SomeColorDataStructure

What would need to go in the function body? I'm not looking for finished code (though I won't refuse it!) just some ideas about what data structures and system calls to use.


Solution

  • This class (from one of this question's answers by @JonnyPiazzi) appears to exactly address my question:

    public static class GradientStopCollectionExtensions
    {
        public static Color GetRelativeColor(this GradientStopCollection gsc, double offset)
        {
            GradientStop before = gsc.Where(w => w.Offset == gsc.Min(m => m.Offset)).First();
            GradientStop after = gsc.Where(w => w.Offset == gsc.Max(m => m.Offset)).First();
    
            foreach (var gs in gsc)
            {
                if (gs.Offset < offset && gs.Offset > before.Offset)
                {
                    before = gs;
                }
                if (gs.Offset > offset && gs.Offset < after.Offset)
                {
                    after = gs;
                }
            }
    
            var color = new Color();
    
            color.ScA = (float)((offset - before.Offset) * (after.Color.ScA - before.Color.ScA) / (after.Offset - before.Offset) + before.Color.ScA);
            color.ScR = (float)((offset - before.Offset) * (after.Color.ScR - before.Color.ScR) / (after.Offset - before.Offset) + before.Color.ScR);
            color.ScG = (float)((offset - before.Offset) * (after.Color.ScG - before.Color.ScG) / (after.Offset - before.Offset) + before.Color.ScG);
            color.ScB = (float)((offset - before.Offset) * (after.Color.ScB - before.Color.ScB) / (after.Offset - before.Offset) + before.Color.ScB);
    
            return color;
        }
    }