[英]How do I cut out a certain part of a spritesheet and display it without the spritesheet's background in WPF C#?
我正在WPF中制作一個小游戲,我想使用從另一個游戲的安裝文件夾中提取的Spritesheet來使角色的動作連續不斷。
我不知道如何在不“分離”黑色背景的情況下裁剪出子畫面圖像的所需部分。
這是一張顯示我角色的各種動作的電子表格
我只能使用從System.Windows.Media.Drawing
或System.Windows.Media.Visual
類繼承的用於可視化的類
(這是在大學的一項任務,他們使我們從其中一項中進行選擇)
如果不需要用代碼解決此問題,一種快速的解決方案是使用圖像編輯應用程序:
將背景轉換為透明度。 我在幾秒鍾內使用paint.net對魔術棒的公差設置為0對您的圖像進行了此操作。
否則請使用不透明蒙版 。
盡管不符合分配條件,但另一個解決方案是在運行時替換所有背景像素。 如果執行此操作,請將結果保存到磁盤,以便僅產生一次費用。 這本質上是我描述的第一個解決方案的DIY。 即
// someBitmap is the bitmap you want to manipulate.
// Ensure we're reading from a bitmap in Bgra32 format.
var srcBitmap = someBitmap.Format == PixelFormats.Bgra32 ?
(BitmapSource)someBitmap : new FormatConvertedBitmap(someBitmap, PixelFormats.Bgra32, null, 0);
// Copy the pixels of the source image to a buffer we can use.
var width = srcBitmap.PixelWidth;
var height = srcBitmap.PixelHeight;
var stride = width * 4;
var byteCount = height * stride;
var srcData= new byte[byteCount];
srcBitmap.CopyPixels(srcData, stride, 0);
var destBitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);
var destData = new byte[byteCount];
// The channel offsets for PixelFormats.Bgra32.
const int BlueOffset = 0;
const int GreenOffset = 1;
const int RedOffset = 2;
const int AlphaOffset = 3;
// Copy the image, filtering out the background.
for (var y = 0; y < height; y++) { // Each column.
for (var x = 0; x < width; x++) { // Each row.
var i = (y * width + x) * 4; // The offset of this pixel in both srcBytes and destBytes.
var b = srcData[i + BlueOffset];
var g = srcData[i + GreenOffset];
var r = srcData[i + RedOffset];
var a = srcData[i + AlphaOffset];
// The "filter".
if (b == 0 && g == 0 && r == 0 && a == 255) {
// The pixel is solid black(the background color), set to transparent.
a = 0;
}
destData[i + BlueOffset] = b;
destData[i + GreenOffset] = g;
destData[i + RedOffset] = r;
destData[i + AlphaOffset] = a;
}
}
// Update the final image with the filtered buffer.
destBitmap.WritePixels(new Int32Rect(0, 0, width, height), destData, stride, 0);
// Finally, convert destBitmap to a BitmapImage and use that in place of someBitmap.
見這個答案轉換destBitmap
到BitmapImage
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.