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

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

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.

回答1:

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;     } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!