使用c#在DrawingContext中绘制折线

时间:2014-03-28 21:22:15

标签: c# wpf

我想在Polyline中绘制Visual Layer。这是我用来绘制Line的代码。我应该绘制多个Lines并将其添加到VisualCollection还是有更好的方式?

var drawingVisual = new DrawingVisual();
using (var dc = drawingVisual.RenderOpen())
{
    var myPen = new Pen
    {
        Thickness = thickness,
        Brush = Settings.GridColor
    };
    myPen.Freeze();
    dc.DrawLine(myPen, pt1, pt2);
}

2 个答案:

答案 0 :(得分:4)

我认为使用DrawGeometry比使用DrawLine更好。

示例:

var myPen = new Pen
{
    Thickness = thickness,
    Brush = Settings.GridColor
};
myPen.Freeze();


var geometry = new StreamGeometry();
using (StreamGeometryContext ctx = geometry.Open())
{
    ctx.BeginFigure(new Point(10, 100), true /* is filled */, true /* is closed */);
    ctx.LineTo(new Point(100, 100), true /* is stroked */, false /* is smooth join */);
    ctx.LineTo(new Point(100, 50), true /* is stroked */, false /* is smooth join */);
}
geometry.Freeze();

dc.DrawGeometry(null, myPen, geometry);

答案 1 :(得分:1)

我不认为有更好的方法,除了调用myPen.Freeze()我只会将其创建为const。我不知道这是否真的更有效,我只是认为它将来会更多地清除代码。我也会(个人事物)不使用var关键字,因为当您拨打drawingVisual.RenderOpen()时,您创建的类型会更不明确。