DrawingContext.DrawGeometry绘制带间隙的相邻几何

时间:2013-09-20 11:17:31

标签: c# wpf

使用DrawingContext.DrawingGeometry我正在绘制两个具有共同边缘的三角形。我想要填充此三角形,但不要用笔抚摸,因为笔具有厚度,并且生成的三角形将比预期的厚度大一半。使用下面附带的代码我得到了奇怪的结果(见图) - 三角形之间有一个小的差距。我究竟做错了什么?有没有比在共同边缘画出额外线更好的方法呢?

XAML:

<Window x:Class="LearnDrawing.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:LearnDrawing" xmlns:wpfApplication1="clr-namespace:WpfApplication1"
        Title="Window1"
        Height="500"
        Width="500">
    <Grid>
        <wpfApplication1:DrawIt Width="400" Height="400" />
    </Grid>
</Window>

代码:

using System.Windows;
using System.Windows.Media;

namespace WpfApplication1
{
   class DrawIt : FrameworkElement
   {
      VisualCollection visuals;

      public DrawIt()
      {
         visuals = new VisualCollection(this);

         this.Loaded += new RoutedEventHandler(DrawIt_Loaded);
      }

      void DrawIt_Loaded(object sender, RoutedEventArgs e)
      {         
         var visual = new DrawingVisual();
         using (DrawingContext dc = visual.RenderOpen())
         {               
            var t1 = CreateTriangleGeometry(new Point(0, 0), new Point(200, 0), new Point(0, 200));
            var t2 = CreateTriangleGeometry(new Point(200, 0), new Point(200, 200), new Point(0, 200));
            dc.DrawGeometry(Brushes.Black, null, t1);             
            dc.DrawGeometry(Brushes.Black, null, t2);
         }
         visuals.Add(visual);
      }

      static PathGeometry CreateTriangleGeometry(Point aPt1, Point aPt2, Point aPt3)
      {
         var figure = new PathFigure();
         figure.StartPoint = aPt1;
         figure.Segments.Add(new PolyLineSegment(new []{aPt2, aPt3}, true));

         var pg = new PathGeometry();
         pg.Figures.Add(figure);
         figure.IsClosed = true;
         figure.IsFilled = true;

         return pg;
      }

      protected override Visual GetVisualChild(int index)
      {
         return visuals[index];
      }

      protected override int VisualChildrenCount
      {
         get
         {
            return visuals.Count;
         }
      }
   }
}

结果:

Result screenshot

1 个答案:

答案 0 :(得分:1)

您可以将视觉效果的EdgeMode设置为EdgeMode.Aliased

public DrawIt()
{
    RenderOptions.SetEdgeMode(this, EdgeMode.Aliased);
    ...
}

另请参阅Visual.VisualEdgeMode属性。