2014-05-05 22 views
2

我重寫邊境控制,在我重寫的OnRender我做的:爲什麼我的座標(1,1)從(0,1)開始?

protected override void OnRender(System.Windows.Media.DrawingContext dc) 
     { 
      this.SnapsToDevicePixels = true; 
      this.VisualEdgeMode = EdgeMode.Aliased; 
      var myPen = new Pen(new SolidColorBrush(Colors.LightGray), 1); 
      dc.DrawLine(myPen, new Point(1, 1), new Point(1, RenderSize.Height - 1)); 
      return; 

這給了我這樣的結果: enter image description here

問:

是否有人能告訴我爲什麼我的代碼畫一條從(0,1)開始的行,而假設從(1,1)開始,就像寫在代碼中一樣?

我的DPI都是96,96

對於裁判,這是我的XAML:

<Window xmlns:MyControls="clr-namespace:MyControls;assembly=MyControls" x:Class="TestControls.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="Auto"></RowDefinition> 
      <RowDefinition></RowDefinition> 
      <RowDefinition></RowDefinition> 
     </Grid.RowDefinitions> 

     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="Auto"></ColumnDefinition> 
      <ColumnDefinition></ColumnDefinition> 
      <ColumnDefinition></ColumnDefinition> 
     </Grid.ColumnDefinitions> 


     <MyControls:Border3D BorderThickness="3" BorderBrush="Aqua"> 
      <Rectangle Width="74" Height="3" HorizontalAlignment="Left"> 
       <Rectangle.Fill> 
        <SolidColorBrush Color="#40FF0000"> 

        </SolidColorBrush> 
       </Rectangle.Fill> 
      </Rectangle> 
     </MyControls:Border3D> 

     <Rectangle Grid.Row="1" Grid.Column="0" Width="80" Grid.ColumnSpan="2" HorizontalAlignment="Left"> 
      <Rectangle.Fill> 
       <SolidColorBrush Color="LightGray"></SolidColorBrush> 
      </Rectangle.Fill> 
     </Rectangle> 

    </Grid> 
</Window> 
+0

,這種行爲是否仍然發生? – Kcvin

+0

看來,我猜你沒有計算邊界線..所以當你試圖畫(1,1)你在screeen上看到(0,1)..試試這個:new Point(1+ border。 TopLine.Height,1 + border.LeftWall.width)注意:給定的代碼是PSEUDO,因此可能在.NET中找不到方法/字段爲相同的名稱 – sihirbazzz

+0

謝謝。克萊門斯似乎對我的答案有確切的答案,並且我會說一些很好的額外解釋:-)! –

回答

2

記住(0, 0)不是左上像素的中心。相反,它是該像素的左上角。爲了繪製的1在第二像素列(索引1)的中間筆畫粗細的線,你就必須吸取(1.5, 1)(1.5, RenderSize.Height - 1)

dc.DrawLine(myPen, new Point(1.5, 1), new Point(1.5, RenderSize.Height - 1)); 

設置SnapsToDevicePixels = true使你的線捕捉到剩下半個像素。


如果你會使用PenLineCap.Square兩個行的筆的StartLineCapEndLineCap屬性,你可以從只有一個像素中心提請其他:如果您更改寬度526

var myPen = new Pen(Brushes.LightGray, 1); 
myPen.StartLineCap = PenLineCap.Square; 
myPen.EndLineCap = PenLineCap.Square; 
dc.DrawLine(myPen, new Point(1.5, 1.5), new Point(1.5, RenderSize.Height - 1.5)); 
+0

非常感謝Clemens。非常乾淨的解釋。我想知道你是否有閱讀書籍的建議來理解WPF的每一個方面,從而吸取這些細微的東西? –

+1

Adam Nathan的* WPF Unleashed *有關於2D圖形的全面章節,它應該給你一個很好的起點。還有一些關於MSDN的詳細文章。 – Clemens

+0

非常感謝Clemens!我會讀它! –

相關問題