【问题标题】:WPF: Stretch rectangle if aspect ratio > 16:9, scale otherwiseWPF:如果纵横比> 16:9,则拉伸矩形,否则缩放
【发布时间】:2019-07-26 09:09:00
【问题描述】:

我正在尝试将一个矩形放在一个会定期更改大小的窗口中的网格中。我不是在使用绝对值,而是使用比率。

因此,矩形相对于窗口/网格可能具有三种状态:

  • 窗口的默认纵横比为 16:9。如果窗口具有该大小,则矩形应该完全适合窗口,填满窗口;
  • 如果窗口的宽度大于该宽度,矩形应随之拉伸。 (所以如果窗口的纵横比 > 16/9,矩形会拉伸它的宽度,因此仍然会填满整个窗口);
  • 如果窗口的高度大于 16:9 的比例,则内部的矩形应 (1) 不垂直拉伸,并且 (2) 与网格底部对齐。

This image explains it a lot clearer

我正在寻找一种不涉及更改 XAML 以外的代码的解决方案(因此 .cs 文件中没有任何内容),除非没有其他方法。我确实尝试过使用 C# 代码找到解决方案:

RectName_OnSizeChanged(object sender, SizeChangedEventArgs) {
    RectName.MaxHeight = 9/16 * RectName.Width;
}

但它似乎不起作用。 (为什么会这样,这是我的奖励问题)

【问题讨论】:

  • 整数 9/16 * anything = 零。试试9 * RectName.Width / 16

标签: c# wpf layout scaling aspect-ratio


【解决方案1】:

这个怎么样:

<Grid Background="CornflowerBlue" SizeChanged="ParentSizeChanged">
    <Rectangle x:Name="theRect" Fill="Blue" HorizontalAlignment="Left" VerticalAlignment="Bottom" />
</Grid>

还有这个:

private void ParentSizeChanged(object sender, SizeChangedEventArgs e)
{
    var parent = sender as FrameworkElement;
    if (parent == null)
        return;
    theRect.Width = parent.ActualWidth;
    theRect.Height = Math.Min(parent.ActualHeight, parent.ActualWidth * 6 / 9);
}

【讨论】:

  • 当窗口的宽度被拉伸时,矩形在窗口后面垂直扩展。我希望它在宽度上拉伸并与窗口具有相同的高度。
  • 答案已更新。再看一遍,我意识到大小将包括父窗口的标题和边框,最简单的解决方案是向父对象添加一个大小处理程序,在我的示例中是一个网格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-25
  • 2011-08-26
  • 2017-07-30
  • 2019-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多