2010-10-27 99 views
3

下面的代碼在畫布上繪製兩條垂直線。這些線條在屏幕上顯示爲不同的厚度,儘管它們在代碼中是相同的。我正在尋找一種方法讓它們看起來像畫布邊框一樣鋒利。設置Path.SnapsToDevicePixels沒有任何作用。代碼是一個人爲的例子,一般來說,繪製這些線條的畫布可以嵌套在視覺樹的更深處。別名問題

感謝您的幫助 康斯坦丁


<Window x:Class="wpfapp.MyWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Grid> 
    <Border BorderBrush="Black" 
      BorderThickness="1" 
      Margin="10"> 
     <Canvas x:Name="Canvas" 
       SizeChanged="OnCanvasSizeChanged" /> 
    </Border> 
    </Grid> 
</Window> 

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

namespace wpfapp 
{ 
    public partial class MyWindow : Window 
    { 
     public MyWindow() 
     { 
      InitializeComponent(); 
     } 

     private void OnCanvasSizeChanged(object sender, SizeChangedEventArgs e) 
     { 
      StreamGeometry g = new StreamGeometry(); 
      double h = this.Canvas.ActualHeight; 

      using (StreamGeometryContext c = g.Open()) 
      { 
       c.BeginFigure(new Point(7, 0), false, false); 
       c.LineTo(new Point(7, h), true, false); 

       c.BeginFigure(new Point(14, 0), false, false); 
       c.LineTo(new Point(14, h), true, false); 
      } 
      g.Freeze(); 

      Path p = new Path(); 

      p.Data = g; 
      p.SnapsToDevicePixels = true; 
      p.Stroke = new SolidColorBrush(Colors.Black); 
      p.StrokeThickness = 1; 

      this.Canvas.Children.Clear(); 
      this.Canvas.Children.Add(p); 
     } 
    } 
} 
+0

只是一種預感,但儘量在包含畫布樹中的每個元素上設置SnapsToDevicePixels。如果將矢量轉換爲渲染流水線上的未對齊座標,則將單個元素捕捉到設備像素無濟於事。 – 2010-10-27 15:08:17

回答

2

需要使用GuidelineSet:


     protected override void OnRender(DrawingContext c) 
     { 
      base.OnRender(c); 

      Pen pen = new Pen(Brushes.Black, 1); 
      double h = this.ActualHeight; 
      double d = pen.Thickness/2; 

      foreach (double x in new double[] { 7, 14 }) 
      { 
       GuidelineSet g = new GuidelineSet(new double[] { x + d }, 
                new double[] { 0 + d, h + d }); 

       c.PushGuidelineSet(g); 
       c.DrawLine(pen, new Point(x, 0), new Point(x, h)); 
       c.Pop(); 
      } 
     }