我正在嘗試使用 CroppedBitmap 在 WPF Image 元素上顯示 PNG 檔案的一部分。
作為測驗,我有以下代碼:
BitmapImage StandardTilesetImage = new BitmapImage();
StandardTilesetImage.BeginInit();
StandardTilesetImage.CacheOption = BitmapCacheOption.OnLoad;
StandardTilesetImage.UriSource = new Uri(pngFilePath, UriKind.Relative);
StandardTilesetImage.EndInit();
// TestImage is an Image object defined in XAML
TestImage.Source = StandardTilesetImage;
這會產生預期的結果 - 影像正確顯示:

作為參考,pngFilePath 是一個指向絕對位置 ( c:/etc/etc/StandardTilesetIcons.png) 的字串,它是一個 512x512 PNG:

如果我修改上面的代碼以剪裁一部分 PNG(例如繪制左上角 64x64 區域),則 TestImage 不再顯示任何內容。
BitmapImage StandardTilesetImage = new BitmapImage();
StandardTilesetImage.BeginInit();
StandardTilesetImage.CacheOption = BitmapCacheOption.OnLoad;
StandardTilesetImage.UriSource = new Uri(pngFilePath, UriKind.Relative);
StandardTilesetImage.EndInit();
CroppedBitmap croppedBitmap = new CroppedBitmap();
croppedBitmap.SourceRect = new Int32Rect(0,0,64, 64);
croppedBitmap.Source = StandardTilesetImage;
TestImage.Source = croppedBitmap;

我希望在我的 TestImage 物件中看到 PNG 的一部分。為什么什么都沒有出現?
uj5u.com熱心網友回復:
就像 BitmapImage 一樣,CroppedBitmap 實作了ISupportInitialize介面,這意味著當您通過默認建構式創建實體時,您必須在設定其任何屬性之前和之后呼叫BeginInit()和方法。EndInit()
或者,使用適當的建構式和兩個類提供的引數:
BitmapImage standardTilesetImage = new BitmapImage(
new Uri(pngFilePath, UriKind.RelativeOrAbsolute));
CroppedBitmap croppedBitmap = new CroppedBitmap(
standardTilesetImage, new Int32Rect(0,0,64, 64));
TestImage.Source = croppedBitmap;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/429681.html
上一篇:使用C#變數設定XAML屬性
下一篇:將值添加到LiveChartc#
