[英]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;
}
圖像元素的大小受其包含面板的影響,但這在任何面板中都可以使用。
<Grid>
<Image Source='flower.png' Width='120' Stretch='Uniform'/>
</Grid>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.