2

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

结果:

结果截图

4

1 回答 1

1

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

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

另请参阅Visual.VisualEdgeMode属性。

于 2013-09-20T11:40:43.343 回答