我在 WPF 中的网格上设置了一个图像控件:
<Window x:Class="Window.PhotoViewer"
Title="PhotoViewer" Height="768" Width="1024" BorderThickness="0,0,0,0">
<Grid Name="ViewerGrid">
<Image Name="imageBox" Width="980" Height="615" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,50,0,0" Stretch="None" />
</Grid>
我使用函数TransformToAncestor来获取 imageBox 的位置:
Point leftTop = imageBox.TransformToAncestor(this).Transform(new Point(-imageBox.ActualWidth/2, -imageBox.ActualHeight/2));
Point rightButtom = imageBox.TransformToAncestor(this).Transform(new Point(imageBox.ActualWidth/2, imageBox.ActualHeight/2));
然后我画一条线来连接这两点:
Line line = new Line();
line.Stroke = System.Windows.Media.Brushes.OrangeRed;
line.X1 = leftTop.X;
line.Y1 = leftTop.Y;
line.X2 = rightButtom.X;
line.Y2 = rightButtom.Y;
line.HorizontalAlignment = HorizontalAlignment.Center;
line.VerticalAlignment = VerticalAlignment.Center;
line.StrokeThickness = 5;
ViewerGrid.Children.Add(line);
结果是错误的。当对齐为中心时如何获得控制器的正确位置?