我正在研究Windows 8 Phone app
,我的应用程序中显示了一些图像,我拥有的图像非常大,质量很好,现在在我的应用程序中我需要在不干扰纵横比的情况下调整图像大小。
我搜索了它,找不到合适的灵魂。
如何实现这一点?
这是我.CS文件中的代码。
string imageName= "path to folder" + name + ".png";
BitmapImage bmp = new BitmapImage(new Uri(imageName, UriKind.Relative));
Image.Source = bmp;
编辑
详细信息:目前我在列表框中显示图像,因此图像看起来非常大,因此我想将其减小到较小的尺寸,而不会影响图像的纵横比。
如果要将缩小的图像加载到内存中,请在不设置
DecodePixelHeight
的情况下设置DecodePixelWidth
(或其他方式)
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:tempsource.png");
float factor = originalImage.Width / (float)_newWidth;
int newHeight = (int)(originalImage.Height / factor);
Bitmap resizedImage = ResizeBitmap(originalImage, _newWidth, newHeight);
resizedImage.Save(@"c:temptarget.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>