在DrawingContext中绘制一个填充三角形

时间:2011-01-19 07:43:36

标签: c# .net wpf

这是此question

的后续内容

问题:

我正在尝试使用DrawingContext绘制一个填充的三角形,它在DrawingVisual上呈现

目前,我已设法使用以下C#代码绘制三角形的轮廓:

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

我明白了:

Unfilled Triangle

如何绘制一个三角形,除了我绘制的边框还有红色填充?

Filled Triangle

2 个答案:

答案 0 :(得分:20)

使用dc.DrawGeometry创建填充的形状。

编辑:这:

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

另一方面,如果您必须创建PathGeometry并且使用DrawGeometry,您也可以使用它,那么您就不需要原始线条图。

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

答案 1 :(得分:4)

也许有点旧但可能对其他人有所帮助。它不使用PathGeometry,而是使用Stream几何。 " 此几何体是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);

有关StreamGeometry的更多信息: https://msdn.microsoft.com/en-us/library/system.windows.media.streamgeometry.aspx

问候。