gpt4 book ai didi

c# - 如何在 WPF C# 中对一行进行部分着色(来自代码隐藏)?

转载 作者:行者123 更新时间:2023-11-30 20:16:55 24 4
gpt4 key购买 nike

enter image description here

A 到 B 行是初始行(以黑色填充)。我正在使用

绘制它
Rectangle = System.Windows.Shapes.Rectangle

我需要将从 A1 点到 B 点的同一条线部分着色为红色(如图所示)。

我如何从代码隐藏中实现它?

注意:我没有能力在这里重新创建(重画)这条线。我只需要对已经存在的线条进行部分着色,并根据其他条件,我可能需要将其恢复为黑色。

最佳答案

要创建简单的双色渐变,您需要在同一位置添加两个渐变停止点,以确保颜色不会从一种颜色慢慢淡入另一种颜色。下面的帮助器类演示了它是如何工作的:

public static class GradientGenerator
{
public static Brush GenerateTwoColorBrush(Color color1, Color color2, double ratio)
{
GradientStopCollection collection = new GradientStopCollection();

collection.Add(new GradientStop(color1, 0));
collection.Add(new GradientStop(color1, ratio));
collection.Add(new GradientStop(color2, ratio));
collection.Add(new GradientStop(color2, 1.0));

LinearGradientBrush brush = new LinearGradientBrush(collection);
return brush;
}
}

在代码隐藏中,您可以简单地调用生成器的方法,以指定的比例(0.0 - 1.0)获取两种颜色的渐变:

rectBlack.Fill = GenerateTwoColorBrush(Colors.Black, Colors.Red, 0.5);

如果您需要水平或倾斜渐变,只需设置 LinearGradientBrushStartPointEndPoint 属性即可。

预期结果:

How it would / should look


如果您决定采用更类似于 MVVM 的方法,或者在 XAML 中创建树,您只需将此方法与 IValueConverter 结合使用即可自动更新 Brush。

public class RatioToGradientConverter : IValueConverter
{
public Color Color1 { get; set; }
public Color Color2 { get; set; }

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double ratio = 0;
if (value is double)
ratio = (double) value;

return GradientGenerator.GenerateTwoColorBrush(Color1, Color2, ratio);
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}

上面的例子是这样制作的:

<Grid>
<Grid.Resources>
<local:RatioToGradientConverter Color1="Black" Color2="Red" x:Key="gradientConverter"/>
</Grid.Resources>
<Rectangle Width="10" Height="200" Name="rect1"
Fill="{Binding ElementName=slider, Path=Value, Converter={StaticResource gradientConverter}}" />
<Slider Height="200" Orientation="Vertical" Minimum="0" Maximum="1" Name="slider"/>
</Grid>

关于c# - 如何在 WPF C# 中对一行进行部分着色(来自代码隐藏)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47527700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com