WPF Shape边界矩形始终为空

时间:2016-05-28 19:59:05

标签: wpf

我的WPF应用程序中有以下代码:

public MainWindow()
    {
        InitializeComponent();
        p1 = new Point(50, 50);
        p2 = new Point(355, 50);
        p3 = new Point(50, 355);
        p4 = new Point(355, 355);

        Loaded += (x, y) => Draw();
        //ContentRendered += (x, y) => Draw();
    }

我创建了一个多边形形状并尝试将其边界矩形以多种方式

 private void Draw()
    {
        Polygon polygon = new Polygon();
        polygon.Stroke = System.Windows.Media.Brushes.White;
        polygon.Points.Add(p1);
        polygon.Points.Add(p2);
        polygon.Points.Add(p3);
        polygon.Points.Add(p4);
        canvas.Children.Add(polygon);
        boundingRect = polygon.TransformToVisual(canvas).TransformBounds(new Rect(polygon.RenderSize));
        boundingRect = polygon.TransformToVisual(polygon).TransformBounds(System.Windows.Controls.Primitives.LayoutInformation.GetLayoutSlot(polygon));
        boundingRect = polygon.RenderTransform.TransformBounds(new Rect(polygon.RenderSize));
        boundingRect = GetRectOfObject(polygon);
        boundingRect = polygon.RenderedGeometry.Bounds;
    }

 private Rect GetRectOfObject(FrameworkElement _element)
    {
        Rect rectangleBounds = new Rect();
        rectangleBounds = _element.RenderTransform.TransformBounds(new Rect(0, 0, _element.ActualWidth, _element.ActualHeight));
        return rectangleBounds;
    }

但是,我总是得到{0; 0; 0; 0}。

在调试时,我可以看到点,但它的大小呈现为0:

enter image description here

我应该如何计算正确的方法?

1 个答案:

答案 0 :(得分:0)

根据mixins方法的MSDN评论,调用UpdateLayout将获得必要的数据(虽然应该小心处理),这样测量工作方式:

private void Draw()
{
    Polygon polygon = new Polygon();
    polygon.Stroke = System.Windows.Media.Brushes.White;
    polygon.Points.Add(p1);
    polygon.Points.Add(p2);
    polygon.Points.Add(p3);
    polygon.Points.Add(p4);
    canvas.Children.Add(polygon);
    polygon.UpdateLayout();
    boundingRect = polygon.TransformToVisual(canvas).TransformBounds(new Rect(polygon.RenderSize));       
}

感谢@ChrisF的提示。