LinearGradientBrush,行之外的gradientstops

时间:2012-06-06 20:39:49

标签: wpf drawing lineargradientbrush

我正在尝试在我的WPF应用程序中绘制类似于soundcloud.com上使用的波形 我是通过绘制多条垂直线

来做到这一点的

我想要的是所有线条都有相同的颜色过渡 (所以水平所有像素都有相同的颜色) 因为并非所有行都具有相同的长度,所以每行在行的末尾都有不同的颜色。

LinearGradientBrush有很多构造函数,最适合我需要的构造函数似乎是LinearGradientBrush(GradientStopCollection,Point,Point)。

Msdn article on the LinearGradientContstructor

有了这些点,我似乎能够将我的GradientStops设置在绘制线之外

我遇到的问题是我不知道如何使用积分。

var r = new GradientStopCollection();
r.Add(new GradientStop(Colors.Black, 0));
r.Add(new GradientStop(Colors.Red, 0.5));
r.Add(new GradientStop(Colors.Black, 1));

//this would be my main gradient background for all my lines (100%)
for (int i = 0; i < 25; i++)
{
  var line = new Line { X1 = i, X2 = i, Y1 = 0, Y2 = 200, Stroke = new LinearGradientBrush(r), StrokeThickness = 1 };
  WaveformCanvas.Children.Add(line);
}
//this would be an actual value of the waveform, points 0,0 and 1,1 seem to indicate that the gradientstops are exactly on the y1/y2
for (int i = 25; i < 50; i++)
{
  var line = new Line { X1 = i, X2 = i, Y1 = 50, Y2 = 150, Stroke = new LinearGradientBrush(r, new Point(0, 0), new Point(1, 1)), StrokeThickness = 1 };
  WaveformCanvas.Children.Add(line);
}
//these point values seem to be about correct for the current line length
//I came to these values by trial and error
for (int i = 50; i < 75; i++)
{
  var line = new Line { X1 = i, X2 = i, Y1 = 50, Y2 = 150, Stroke = new LinearGradientBrush(r, new Point(-0.5, -0.5), new Point(1.5, 1.5)), StrokeThickness = 1 };
  WaveformCanvas.Children.Add(line);
}

我很困惑为什么这些点是2d坐标,因为带有点-0.5,-0.5的渐变似乎没有与绘制线不同的角度

所以我需要了解如何相对于我的“主要100%渐变”放置点

或者更简单的方法就是用纯色绘制线条,然后使用某种颜色选择以矩形渐变作为背景替换黑色像素。

1 个答案:

答案 0 :(得分:1)

查看GradientBrush.MappingMode Property

LinearGradientBrush(GradientStopCollection, Point, Point)会使用BrushMappingMode.RelativeToBoundingBox初始化画笔,但我认为您需要BrushMappingMode.Absolute。没有构造函数重载。所以你必须自己设置这个属性。

LinearGradientBrush brush = new LinearGradientBrush(r, new Point(0, 0), new Point(0, 200));
brush.MappingMode = BrushMappingMode.Absolute;