【发布时间】:2020-05-30 09:35:29
【问题描述】:
我目前在使用 RotateTransform 和 LayoutTransform 在 WPF 中旋转图像时遇到问题。当图像的像素高度大于显示器高度并旋转 90º 或 270º 时,窗口大小将高于显示器屏幕分辨率大小。
示例截图: Application running with image at 90º Application running with image at 0º
我正在使用下面的代码(简化),其中 mainWindow.img 是 System.Windows.Control.Image:
static void Rotate(int degrees)
{
var rt = new RotateTransform { Angle = degrees };
mainWindow.img.LayoutTransform = rt;
}
这是一个图片查看器项目,完整的源代码可以在https://github.com/Ruben2776/PicView获得
我已经尝试改变图像的宽度和高度值,但它会产生不希望的结果(倾斜的比例)。
图像尺寸的尺寸计算是根据用户的屏幕高度进行的,使用以下修剪代码:
int interfaceHeight = 90;
double maxWidth = Math.Min(MonitorInfo.Width, width);
double maxHeight = Math.Min((MonitorInfo.Height - interfaceHeight), height);
double AspectRatio = Math.Min((maxWidth / width), (maxHeight / height));
mainWindow.img.Width = (width * AspectRatio);
mainWindow.img.Height = (height * AspectRatio);
height 和 width 是图像的尺寸,MonitorInfo 是检索当前显示器分辨率的类。
更新
以下是说明问题的示例 WPF 应用程序的最少代码:
MainWindow.xaml
<Window x:Class="RotateTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
SizeToContent="WidthAndHeight"
Title="MainWindow" >
<Grid>
<Image x:Name="img" Stretch="Fill" Source="https://w.wallhaven.cc/full/nk/wallhaven-nkrwz1.jpg"/>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace RotateTest
{
public partial class MainWindow : Window
{
int Degrees;
public MainWindow()
{
InitializeComponent();
ContentRendered += MainWindow_ContentRendered;
KeyDown += MainWindow_KeyDown;
}
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Up:
Rotate(true);
break;
case Key.Down:
Rotate(false);
break;
}
}
private void MainWindow_ContentRendered(object sender, EventArgs e)
{
int interfaceHeight = 90;
double maxWidth = Math.Min(SystemParameters.PrimaryScreenWidth, img.Source.Width);
double maxHeight = Math.Min(SystemParameters.PrimaryScreenHeight - interfaceHeight, img.Source.Height);
double AspectRatio = Math.Min((maxWidth / img.Source.Width), (maxHeight / img.Source.Height));
img.Width = (img.Source.Width * AspectRatio);
img.Height = (img.Source.Height * AspectRatio);
}
void Rotate(int degrees)
{
var rt = new RotateTransform { Angle = Degrees = degrees };
img.LayoutTransform = rt;
}
void Rotate(bool right)
{
switch (Degrees)
{
case 0:
if (right)
{
Rotate(270);
}
else
{
Rotate(90);
}
break;
case 90:
if (right)
{
Rotate(0);
}
else
{
Rotate(180);
}
break;
case 180:
if (right)
{
Rotate(90);
}
else
{
Rotate(270);
}
break;
case 270:
if (right)
{
Rotate(180);
}
else
{
Rotate(0);
}
break;
}
}
}
}
【问题讨论】:
标签: c# wpf image-rotation