问题描述
如果我们将 WPF (Silverlight) Viewbox
与 Stretch="UniformToFill"
或 Stretch="Uniform"
一起使用,它会保留内容的本机宽高比,我们如何知道当前应用于内容的缩放系数?
In case we use WPF (Silverlight) Viewbox
with Stretch="UniformToFill"
or Stretch="Uniform"
when it preserves content's native aspect ratio, how could we get knowing the current coefficient of scaling which were applied to the content?
注意:我们并不总是知道内容的确切初始尺寸(例如它是一个包含很多东西的网格).
Note: we not always know the exact initial dimensions of the content (for example it's a Grid with lots of stuff in it).
推荐答案
看到这个问题:获取 ViewBox 中项目的大小(在拉伸"之后)
基本上,如果您有一个名为 viewbox 的 Viewbox
,您可以像这样获得 ScaleTransform
Basically, if you have a Viewbox
called viewbox, you can get the ScaleTransform
like this
ContainerVisual child = VisualTreeHelper.GetChild(viewbox, 0) as ContainerVisual;
ScaleTransform scale = child.Transform as ScaleTransform;
你也可以为 Viewbox
创建一个扩展方法,你可以这样调用
You could also make an extension method for Viewbox
which you can call like this
viewbox.GetScaleFactor();
ViewBoxExtensions
public static class ViewBoxExtensions
{
public static double GetScaleFactor(this Viewbox viewbox)
{
if (viewbox.Child == null ||
(viewbox.Child is FrameworkElement) == false)
{
return double.NaN;
}
FrameworkElement child = viewbox.Child as FrameworkElement;
return viewbox.ActualWidth / child.ActualWidth;
}
}
这篇关于如何获得应用的 WPF Viewbox 缩放系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!