2010-05-26 50 views
6

我有一個自定義的WPF畫布,我想在其上顯示一個網格。我通過覆蓋Canvas上的OnRender方法並使用DrawingContext繪圖函數來完成此操作。 IsGridVisible,GridWidth,GridHeight分別是每個網格線水平和垂直間的像素數。WPF畫布 - 單像素網格

我還使用Canvas.LayoutTransform屬性上的ScaleTransform來放大Canvas項目,正如人們所期望的那樣,網格線粗細乘以ScaleTransform縮放因子,如下圖所示。是否有任何方法繪製單個像素線,而不考慮當前的Canvas RenderTransform?

protected override void OnRender(System.Windows.Media.DrawingContext dc) 
    { 
     base.OnRender(dc); 

     if (IsGridVisible) 
     { 
      // Draw GridLines 
      Pen pen = new Pen(new SolidColorBrush(GridColour), 1); 
      pen.DashStyle = DashStyles.Dash; 

      for (double x = 0; x < this.ActualWidth; x += this.GridWidth) 
      { 
       dc.DrawLine(pen, new Point(x, 0), new Point(x, this.ActualHeight)); 
      } 

      for (double y = 0; y < this.ActualHeight; y += this.GridHeight) 
      { 
       dc.DrawLine(pen, new Point(0, y), new Point(this.ActualWidth, y)); 
      } 
     } 
    } 

alt text http://www.freeimagehosting.net/uploads/f05ad1f602.png

+0

您是否嘗試將筆厚度設置爲1.0 /縮放? – 2010-05-27 00:41:15

+0

謝謝!看來我目前無法思考。 – LiamV 2010-05-27 09:28:58

+1

感謝上面的代碼。過去兩天我一直在尋找這種類型的例子。我已經實現了一個自定義畫布並繪製瞭如圖所示的網格。問題在於它非常緩慢。當我最大化或調整窗口大小時,表現真的很慢。它掛了一點。有沒有解決方案? – 2010-10-18 10:02:07

回答

2

由於意見原職狀態。筆厚度應設置爲1.0 /變焦。