如何从XAML LinearGradientBrush的偏移量中读取颜色?

时间:2013-04-23 05:52:56

标签: wpf xaml lineargradientbrush

给定LinearGradientBrush定义如下:

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

获取该定义并确定由特定偏移量表示的颜色(例如0.13或0.82而不渲染任何内容)需要什么?

这将采用具有这样的原型的函数形式:

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

功能体需要什么?我不是在寻找完成的代码(虽然我不会拒绝它!)只是关于使用什么数据结构和系统调用的一些想法。

1 个答案:

答案 0 :(得分:6)

这门课程(来自one of this question's answers @JonnyPiazzi)似乎完全解决了我的问题:

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