【问题标题】:How do you measure the size of a Path object in WPF/Silverlight?如何在 WPF/Silverlight 中测量 Path 对象的大小?
【发布时间】:2011-11-11 21:18:48
【问题描述】:

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

现在你可以看到的路径只有大约一百个像素大小,但是当读取 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());
        }
    }
}

【问题讨论】:

    标签: wpf silverlight size measurement


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这将被证明是相当棘手的,因为如果路径包含弧并且弧延伸到用于定义路径的坐标/点之外,则很难计算边界框。

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

      【讨论】:

        【解决方案3】:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-17
          • 2010-12-10
          • 2011-04-27
          • 2011-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多