WPF:如何获得形状的真实大小(边界框) [英] WPF: How to get the true size (Bounding Box) of shapes

查看:230
本文介绍了WPF:如何获得形状的真实大小(边界框)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与获得的实际尺寸形状(边框)的麻烦。



我试图同时使用RenderSize和ActualSize但他们返回值是不要 ŧ意义。
但是,使用这些方法的UI元素的伟大工程。



如果你能帮助我这个我会greateful。


< DIV CLASS =h2_lin>解决方案

您可以得到边界框任何视觉使用 TransformToVisual



所以,如果你有一个多边形这样定义

 <帆布NAME =画布> 
<多边形NAME =多边形Canvas.Left =12Canvas.Top =12
点=0,75 100,0 100,150 0.75
行程= 紫
填充=#9999FF
StrokeThickness =1/>
< /帆布>



然后就可以添加边框围绕其边框使用下面的代码

 私人无效AddBorderForFrameworkElement(FrameworkElement的元素)
{
矩形边界=元素.TransformToVisual(画布).TransformBounds(新矩形(element.RenderSize));
边境boundingBox的新= {边境= BorderBrush Brushes.Red,了borderThickness =新的厚度(1)};
Canvas.SetLeft(boundingBox的,bounds.Left);
Canvas.SetTop(boundingBox的,bounds.Top);
boundingBox.Width = bounds.Width;
boundingBox.Height = bounds.Height;
canvas.Children.Add(boundingBox的);
}



但是,您可能并不总是得到预期的结果使用该既然界限不会永远是界什么是真正绘制。如果改为定义多边形象下面这样,你开始画,其中x = 100则边框会大很多又是什么吸引

 <多边形NAME =多边形Canvas.Left =140Canvas.Top =12
点=100,75 200, 0 200150 100,75
行程=紫
填充=#9999FF
StrokeThickness =1/>



在这里输入的形象描述结果
包围盒比较


I'm having trouble with getting the actual size (bounding box) of Shapes.

I tried to use both RenderSize and ActualSize but they return values that don't make sense. However, using these methods for UIElements works great.

if you can help me with this I will be greateful.

解决方案

You can get the Bounding Box for any Visual using TransformToVisual

So if you have a Polygon defined like this

<Canvas Name="canvas">
    <Polygon Name="polygon" Canvas.Left="12" Canvas.Top="12"
             Points="0,75 100,0 100,150 0,75"
             Stroke="Purple"
             Fill="#9999ff"
             StrokeThickness="1"/>
</Canvas>

Then you can add a Border around its Bounding Box with the following code

private void AddBorderForFrameworkElement(FrameworkElement element)
{
    Rect bounds = element.TransformToVisual(canvas).TransformBounds(new Rect(element.RenderSize));
    Border boundingBox = new Border { BorderBrush = Brushes.Red, BorderThickness = new Thickness(1) };
    Canvas.SetLeft(boundingBox, bounds.Left);
    Canvas.SetTop(boundingBox, bounds.Top);
    boundingBox.Width = bounds.Width;
    boundingBox.Height = bounds.Height;
    canvas.Children.Add(boundingBox);            
}

However, you may not always get the desired results using this since the Bounding Box will not always be the Bounds for what is actually drawn. If you instead define your Polygon like below where you start to draw where x=100 then the Bounding Box will be much larger then what is drawn

<Polygon Name="polygon" Canvas.Left="140" Canvas.Top="12"
         Points="100,75 200,0 200,150 100,75"
         Stroke="Purple"
         Fill="#9999ff"
         StrokeThickness="1"/>


Bounding Box comparison

这篇关于WPF:如何获得形状的真实大小(边界框)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆