C# 将窗口大小调整为URL处的图像

C# 将窗口大小调整为URL处的图像,c#,wpf,image,C#,Wpf,Image,图像的源绑定到指向图像的URL 如果URL上的图像比MaxHeight和MaxWidth小,那么下面的代码非常有效。图像大小与url完全相同,并且窗口大小正确 如果URL处的图像大于MaxHeight和MaxWidth,则仅显示图像的一部分。图像不会缩小以适合窗口 如果我删除Stretch=“None”,则大图片会缩小以适合MaxHeight和MaxWidth,看起来很棒,但小图片会扩展以消耗所有可用空间,看起来像垃圾 以下是我一直在测试的两幅图像: 在代码隐藏中,创建一个属性作为 publi

图像的源绑定到指向图像的URL

如果URL上的图像比
MaxHeight
MaxWidth
小,那么下面的代码非常有效。图像大小与url完全相同,并且窗口大小正确

如果URL处的图像大于
MaxHeight
MaxWidth
,则仅显示图像的一部分。图像不会缩小以适合窗口

如果我删除
Stretch=“None”
,则大图片会缩小以适合
MaxHeight
MaxWidth
,看起来很棒,但小图片会扩展以消耗所有可用空间,看起来像垃圾

以下是我一直在测试的两幅图像:


在代码隐藏中,创建一个属性作为

public Point ImageSize {get;set}
从构造函数/Initialize()中的URL获取图像,并相应地设置
ImageSize

将窗口的高度和宽度绑定到
ImageSize.X
ImageSize.Y

Height="{Binding ImageSize.Y}" Width="{Binding ImageSize.Y}"

您可以做的是删除Stretch=“None”,如您所说,使大图像缩小。但是,为了避免放大小图像,只需添加以下属性:

StretchDirection="DownOnly"
这样可以防止小图像向上缩放,并允许缩小大图像。窗口也会适当调整大小

这是我在LinqPad中测试的代码。只需将showLarge更改为true和false即可在图像之间切换

bool showLarge = false;
var w = new Window();

w.ResizeMode = ResizeMode.NoResize;
w.UseLayoutRounding = true;
w.SizeToContent = SizeToContent.WidthAndHeight;
w.MaxHeight = 750;
w.MaxWidth = 750;

Image img = new Image();
img.HorizontalAlignment = HorizontalAlignment.Center;
img.VerticalAlignment = VerticalAlignment.Center;
img.StretchDirection = StretchDirection.DownOnly;
if(showLarge)
    img.Source = new BitmapImage(new System.Uri(@"http://i.imgur.com/iaBp2Fv.jpg"));
else
    img.Source = new BitmapImage(new System.Uri(@"http://i.imgur.com/fiRrTJS.jpg"));

w.Content = img;
w.ShowDialog();

我不认为您可以从XAML实现这一点,但是在代码背后实现这一点应该没有问题。下载图像,找到大小并相应地设置
拉伸
属性。
bool showLarge = false;
var w = new Window();

w.ResizeMode = ResizeMode.NoResize;
w.UseLayoutRounding = true;
w.SizeToContent = SizeToContent.WidthAndHeight;
w.MaxHeight = 750;
w.MaxWidth = 750;

Image img = new Image();
img.HorizontalAlignment = HorizontalAlignment.Center;
img.VerticalAlignment = VerticalAlignment.Center;
img.StretchDirection = StretchDirection.DownOnly;
if(showLarge)
    img.Source = new BitmapImage(new System.Uri(@"http://i.imgur.com/iaBp2Fv.jpg"));
else
    img.Source = new BitmapImage(new System.Uri(@"http://i.imgur.com/fiRrTJS.jpg"));

w.Content = img;
w.ShowDialog();