为什么我的坐标(1,1)从(0,1)开始? [英] Why my coordinate (1,1) start at (0, 1)?
问题描述
我重写了Border控件,并在重写的OnRender中执行了
I overriden Border control and in my overriden OnRender I do:
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;
哪个给我这个结果:
Which give me this result:
问题:
有人可以告诉我为什么我的代码画一条以(0,1)开头的行,而假定它以(1,1)开头,就像用代码编写的那样吗?
我的DPI是96、96.
My DPI are 96, 96.
对于裁判,这是我的xaml:
For ref, this is my 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, 0)
不在左上像素的中心.相反,它是该像素的左上角.为了在第二个像素列(索引为1)的中间绘制笔划粗细为1
的线,您必须从(1.5, 1)
绘制到(1.5, RenderSize.Height - 1)
:
Keep in mind that (0, 0)
is not the center of the upper left pixel. Instead it is the upper left corner of that pixel. In order to draw a line with a stroke thickness of 1
in the middle of the second pixel column (with index 1) you would have to draw from (1.5, 1)
to (1.5, RenderSize.Height - 1)
:
dc.DrawLine(myPen, new Point(1.5, 1), new Point(1.5, RenderSize.Height - 1));
设置SnapsToDevicePixels = true
使您的行向左对齐半个像素.
Setting SnapsToDevicePixels = true
made your line snap to the left by half a pixel.
如果您使用 PenLineCap.Square 对于线条的Pen的StartLineCap
和EndLineCap
属性,您可以从一个像素中心精确地绘制到另一个像素中心:
If you would use PenLineCap.Square for both the StartLineCap
and EndLineCap
properties of the line's Pen, you could draw from exactly one pixel center to the other:
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));
这篇关于为什么我的坐标(1,1)从(0,1)开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!