繁体   English   中英

如何调整图像大小而又不影响纵横比

[英]How to resize the images without disturbing the aspect ratio

我正在使用Windows 8 Phone app ,我的Windows 8 Phone app显示了一些图像,这些图像很大且质量很好,现在在我的应用程序中,我需要调整图像的大小而不会影响宽高比。

我已经搜索了它,却找不到合适的灵魂。

如何实现呢?

这是我在.CS文件中的代码。

string imageName= "path to folder" + name + ".png";
BitmapImage bmp = new BitmapImage(new Uri(imageName, UriKind.Relative));
Image.Source = bmp;

编辑

更多信息:当前我正在列表框中显示图像,因此图像看起来很大,因此我想将其减小到较小的尺寸而不影响图像的纵横比。

如果要将缩小的图像加载到内存中,请设置DecodePixelWidth而不设置DecodePixelHeight (或其他方式)

BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelWidth = 80; 
bitmapImage.UriSource = new Uri(imageName, UriKind.Relative);

编辑

或者,如果要将高分辨率图像保留在内存集中,以进行Image控制。

<Image ... Width="80"/>

Stretch属性在默认情况下设置为Uniform ,这意味着:

调整内容大小以适合目标尺寸,同时保留其原始长宽比。

应该这样做:

static void Main(string[] args)
    {
        int _newWidth = 60; //the new width is set, the height will be calculated

        var originalImage = Bitmap.FromFile(@"C:\temp\source.png");

        float factor = originalImage.Width / (float)_newWidth;
        int newHeight = (int)(originalImage.Height / factor);

        Bitmap resizedImage = ResizeBitmap(originalImage, _newWidth, newHeight);

        resizedImage.Save(@"c:\temp\target.png");
    }

    private static Bitmap ResizeBitmap(Image b, int nWidth, int nHeight)
    {
        Bitmap result = new Bitmap(nWidth, nHeight);
        using (Graphics g = Graphics.FromImage(result))
            g.DrawImage(b, 0, 0, nWidth, nHeight);
        return result;
    }

如果要按比例缩小显示的图像大小,请尝试使用Image控件的Stretch属性,如本博客文章中所演示和很好地说明

<Image x:Name="Image" Stretch="UniformToFill"></Image>

图像元素的大小受其包含面板的影响,但这在任何面板中都可以使用。

<Grid>
    <Image Source='flower.png' Width='120' Stretch='Uniform'/>
  </Grid>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM