我的任务非常简单:从A点到B点画一条线,并在A点和B点设置不同的颜色,例如:白色为A,黑色为B,淡出线条。
我尝试使用LinearGradientBrush执行此操作:
var brush = new LinearGradientBrush(
Color.FromArgb(255, 0, 0, 0),
Color.FromArgb(255, 255, 0, 0), new Point(0, 0), new Point(1,1));
var pen = new Pen(brush, 10.0);
dc.DrawLine(pen, new Point (300, 300), new Point(300, 100));
但是这不会产生想要的结果,因为GradientBrush是根据对象的边界框映射的。因此,从100/100到200/200的线的结果和反方向的线是相同的(这不是我想要的)。
我如何使用WPF解决这个问题?感谢。
编辑:出于性能原因,我需要使用低级图形功能(例如DrawLine),因为我画了很多行。
答案 0 :(得分:1)
How to use a LinearGradientBrush article with examples in both XAML and C# code.
尝试这种方法,请告诉我你需要什么。请注意这条线是相反的方向。
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
var image = new Image
{
Source = new DrawingImage(CreateDrawingVisualRectangle(new Point(300,300), new Point(300,100) ).Drawing),
Stretch = Stretch.None,
};
var image2 = new Image
{
Margin = new Thickness(10, 0, 0, 0),
Source = new DrawingImage(CreateDrawingVisualRectangle(new Point(300, 100), new Point(300, 300)).Drawing),
Stretch = Stretch.None,
};
var stackPanel = new StackPanel() {Orientation = Orientation.Horizontal};
stackPanel.Children.Add(image);
stackPanel.Children.Add(image2);
Content = stackPanel;
}
// Create a DrawingVisual that contains a rectangle.
private DrawingVisual CreateDrawingVisualRectangle(Point start, Point end)
{
DrawingVisual drawingVisual = new DrawingVisual();
// Retrieve the DrawingContext in order to create new drawing content.
DrawingContext drawingContext = drawingVisual.RenderOpen();
// Create a rectangle and draw it in the DrawingContext.
var gradientStopCollection = new GradientStopCollection
{
new GradientStop(Color.FromArgb(255, 0, 0, 0), 0.0),
new GradientStop(Color.FromArgb(255, 255, 0, 0), 0.75)
};
var brush = new LinearGradientBrush(gradientStopCollection);
var pen = new Pen(brush, 10.0);
var vector1 = new Vector(start.X, start.Y);
var vector2 = new Vector(end.X, end.Y);
if (vector1.Length < vector2.Length)
{
brush.StartPoint = new Point(1, 1);
brush.EndPoint = new Point(0, 0);
}
drawingContext.DrawLine(pen, start, end);
drawingContext.Close();
return drawingVisual;
}
}
答案 1 :(得分:0)
画笔上的MappingMode属性允许您指定起点/终点的绝对坐标,或相对于形状边界的坐标:
http://msdn.microsoft.com/en-us/library/system.windows.media.gradientbrush.mappingmode.aspx
答案 2 :(得分:0)
如何使用矩形?
<Rectangle Height="2" Margin="10,0,10,10">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="Transparent" Offset="1.0"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>