自定义画笔 - 我想要两个渐变将它们链接在一起

Log*_*gan 1 c# silverlight wpf user-interface

我正在制作一个条形图,我想要每个条形有两个单独的渐变。首先,我想要一个渐变,从上到下纯红色到透明红色。我想在顶部绘制一个从右到左、黑色到不透明的渐变。

所以 - 在左下角我们应该有;

  • 左下角 - Alpha 0
  • 右下角 - Alpha 0
  • 左上角 - Alpha 255 颜色红色
  • 右上角 - Alpha 255 颜色黑色

所以实际上我想采用纯色,从左到右的渐变添加到黑色,然后获取输出并添加从上到下的渐变到透明度。

所有这一切,我希望它在一个刷子里,这甚至可能吗?

Ray*_*rns 5

是的。使用一个 VisualBrush,其 Visual 是一个边框内的 Rectangle 来组合其他两个画笔。

像这样的东西:

<LinearGradientBrush x:Key="UnderBrush" EndPoint="0,1"> 
  <GradientStop Color="#FFFF0000" Offset="0" /> 
  <GradientStop Color="#00FF0000" Offset="1" /> 
</LinearGradientBrush> 

<LinearGradientBrush x:Key="OverBrush" EndPoint="1,0"> 
  <GradientStop Color="#00000000" Offset="0" /> 
  <GradientStop Color="#FF000000" Offset="1" /> 
</LinearGradientBrush> 

<VisualBrush x:Key="CombinedBrush">
  <VisualBrush.Visual>
    <Border Background="{StaticResource UnderBrush}">
      <Rectangle Fill="{StaticResource OverBrush}" Width="1" Height="1" />
    </Border>
  </VisualBrush.Visual>
</VisualBrush>
Run Code Online (Sandbox Code Playgroud)

可以使用CombinedBrush 来绘制您的条形图,您将获得您所描述的效果。

银光版

由于 Silverlight 没有 VisualBrush,您必须在代码中构建 WritableBitmap 并将其与 ImageBrush 一起使用:

<ImageBrush x:Key="CombinedBrush">
  <my:VisualBrushSimulator.Visual>
    <Border Background="{StaticResource UnderBrush}">
      <Rectangle Fill="{StaticResource OverBrush}" Width="1" Height="1" />
    </Border>
  </my:VisualBrushSimulator.Visual>
</ImageBrush>
Run Code Online (Sandbox Code Playgroud)

下面是 VisualBrushSimulator 的实现方式:

public class VisualBrushSimulator : DependencyObject
{
  public Visual GetVisual(DependencyObject obj) { return (Visual)obj.GetValue(VisualProperty); }
  public void SetVisual(DependencyObject obj, Visual value) { obj.SetValue(VisualProperty, value); }
  public static readonly DependencyProperty VisualProperty = DependencyProperty.RegisterAttached("Visual", typeof(Visual), typeof(VisualBrushSimulator), new PropertyMetadata
  {
    PropertyChangedCallback = (obj, e) =>
    {
      int width=1000;
      int height=1000;
      var bitmap = new WritableBitmap(width, height);
      bitmap.Render((Visual)e.NewValue, new ScaleTransform { ScaleX = width, ScaleY = height });
      ((ImageBrush)obj).ImageSource = bitmap;
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

请注意,这不是真正的 VisualBrush 模拟,因为对 Visual 的更改不会影响画笔。