如何在WPF / Silverlight中测量Path对象的大小?

时间:2011-11-11 21:18:48

标签: wpf silverlight size measurement

我正在研究WPF中的映射系统,并且在处理Path元素时遇到了一些奇怪的行为。我们有一个canvas元素,其中包含路径对象,用于显示地图上的位置。当我尝试通过代码测量它们的大小或位置时,它们的大小始终包括它们与原点的距离(0,0),它们的位置始终位于原点。我无法弄清楚如何测量路径本身的实际可见区域。这是一个例子:

Path Sample

现在你可以看到的路径大小只有大约一百个像素,但是当读取AcutalWidth / ActualHeight属性时,它也包括它与顶部/左角的距离。我也在路径上尝试了.Measure()方法并获得了相同的结果。是否有任何特殊工具可以实际测量路径的可见区域?

以下是此示例的代码供参考:

<Window x:Class="WPF_Testing_Area.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>
        <Canvas x:Name="Wrapper" Width="2185.922" Height="3091.486">
            <Path Fill="#FF9EC99F" MouseLeftButtonDown="Path_MouseLeftButtonDown" Stroke="Black" StrokeThickness="1.5" StrokeStartLineCap="Round" StrokeEndLineCap="Round" StrokeDashCap="Round" StrokeLineJoin="Round" 
                    Data="F1M1501.916,677.412C1480.471,683.851 1457.263,676.647 1443.234,659.196 1441.36,656.865 1439.083,654.889 1436.51,653.362L1436.805,800.23 1533.736,819.855C1537.515,820.62,1541.335,821.166,1545.177,821.49L1501.916,677.412z"/>
        </Canvas>
    </Grid>
</Window>

背后的代码:

using System.Windows;
using System.Windows.Input;
using System.Windows.Shapes;

namespace WPF_Testing_Area
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Path_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var path = sender as Path;
            var size = new Size(path.ActualWidth, ActualHeight);
            MessageBox.Show(size.ToString());

            // try to measure the shape
            path.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            MessageBox.Show(path.DesiredSize.ToString());
        }
    }
}

3 个答案:

答案 0 :(得分:0)

我会尝试从path.ActualWidth的值中减去路径Canvas.Left的值(Canvas.Top和path.ActualHeight也是如此)。我认为这会给你正确的尺寸。

答案 1 :(得分:0)

这将证明是非常棘手的,因为如果路径包含弧并且弧延伸超出用于定义路径的坐标/点,则很难计算边界框。

请参阅:WPF: How to get the true size (Bounding Box) of shapesGetting the true visual bounding box of a WPF element?

答案 2 :(得分:0)

相关问题