简体   繁体   中英

Draw Polyline in DrawingContext using c#

I want to draw a Polyline in the Visual Layer . Here is the code I'm using to draw a Line . Should I draw multiple Lines and add them to the VisualCollection or there is a better way?

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);
}

I think you would be better off using DrawGeometry than DrawLine .

Example:

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);

I don't think there is a better way, except instead of calling myPen.Freeze() I would just create it as a const . I don't know if that is really more efficient, I just think it clears the code up more in the future. I would also (personal thing) not use the var keyword, as it would be less ambiguous what type you create when you call drawingVisual.RenderOpen() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM