确定WPF元素相对于某些父对象的边界rect [英] Determine the bounding rect of a WPF element relative to some parent
问题描述
我认为这是一个非常简单的请求,但是我似乎无法在搜索中找到一个确定的答案.如何确定窗口中特定视觉元素相对于其他父元素的界限?
I consider this a pretty simple request, but I can't seem to find a conclusive answer in my searches. How can I determine the bounds of a particular visual element in my window, relative to some other parent element?
我尝试使用LayoutInformation.GetLayoutSlot
,但这似乎只是在0,0返回Rect
,并且不能反映元素的实际位置.
I've tried using LayoutInformation.GetLayoutSlot
but this just seems to return a Rect
at 0,0 and doesn't reflect the actual location of the element.
我想做的是使用RenderTargetBitmap
对窗口进行截屏",然后将其裁剪为特定的元素,但是我无法获得元素的边界来知道将位图裁剪到什么!
What I'm trying to do is take a "screenshot" of a window using RenderTargetBitmap
and then crop it to a particular element, but I can't get the element's bounds to know what to crop the bitmap to!
推荐答案
这很简单:
public static Rect BoundsRelativeTo(this FrameworkElement element,
Visual relativeTo)
{
return
element.TransformToVisual(relativeTo)
.TransformBounds(LayoutInformation.GetLayoutSlot(element));
}
实际上,将其放在单独的方法中可能会过大.
In fact it may be overkill to put it in a separate method.
这篇关于确定WPF元素相对于某些父对象的边界rect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!