简体   繁体   中英

Draw a filled triangle in DrawingContext

This is a follow up from this question .

Question:

I am trying to draw a filled triangle using DrawingContext , which is rendered on a DrawingVisual

Currently, I have managed to draw the outline of a triangle using the following C# code:

private DrawingVisual CreateTriangle()
  {
     DrawingVisual triangle = new DrawingVisual();
     using ( DrawingContext dc = triangle.RenderOpen() )
     {
         Pen drawingPen = new Pen(Brushes.Black,3);
         dc.DrawLine(drawingPen, new Point(0, 50), new Point(50, 0));
         dc.DrawLine(drawingPen, new Point(50, 0), new Point(50, 100));
         dc.DrawLine(drawingPen, new Point(50, 100), new Point(0, 50));

     }
     return triangle;
  }

I get this:

未填充的三角形

How do I draw a triangle that, in addition to th border I have drawn also has a red fill?

填充三角形

Use dc.DrawGeometry to create filled-in shapes.

Edit: This:

private DrawingVisual CreateTriangle()
{
    var triangle = new DrawingVisual();
    using (DrawingContext dc = triangle.RenderOpen())
    {
       var start = new Point(0, 50);

       var segments = new []
       { 
          new LineSegment(new Point(50,0), true), 
          new LineSegment(new Point(50, 100), true)
       };

       var figure = new PathFigure(start, segments, true);
       var geo = new PathGeometry(new [] { figure });
       dc.DrawGeometry(Brushes.Red, null, geo);

       var drawingPen = new Pen(Brushes.Black, 3);
       dc.DrawLine(drawingPen, new Point(0, 50), new Point(50, 0));
       dc.DrawLine(drawingPen, new Point(50, 0), new Point(50, 100));
       dc.DrawLine(drawingPen, new Point(50, 100), new Point(0, 50));   
    }

    return triangle;
}

On a side note, if you have to create the PathGeometry anyway and you use DrawGeometry you might as well stroke it too, then you don't need your original line drawings.

dc.DrawGeometry(Brushes.Red, new Pen(Brushes.Black, 3), geo);

Maybe a bit old but it might help somebody else. Instead of using PathGeometry it uses Stream geometry. " This geometry is light-weight alternative to PathGeometry "

Point p1 = new Point(0, 50);
Point p2 = new Point(50, 0);
Point p3 = new Point(50, 100);
StreamGeometry streamGeometry = new StreamGeometry();
using (StreamGeometryContext geometryContext = streamGeometry.Open())   
{
    geometryContext.BeginFigure(p1, true, true);
    PointCollection points = new PointCollection{ p2, p3 };
    geometryContext.PolyLineTo(points, true, true);
}

streamGeometry.Freeze();
context.DrawGeometry(Brushes.Red, new Pen(Brushes.Black,3), streamGeometry);

More info about StreamGeometry here: https://msdn.microsoft.com/en-us/library/system.windows.media.streamgeometry.aspx

Regards.

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