XNA 和从文件加载图像
本文关键字:加载 图像 文件 XNA | 更新日期: 2023-09-27 18:30:38
我找到了直接从文件加载图像的方法,但我加载的图像是蓝色的(原始图像是绿色的)。我坚持认为它以不好的方式保存,所以我用 photoshop 保存了它,但没有任何变化。我想我的程序运行不佳。如何更改它,这是从文件加载图像的好方法吗?位图到纹理2d方法:
public static Texture2D GetTexture2DFromBitmap(GraphicsDevice device, Bitmap bitmap)
{
Texture2D tex = new Texture2D(device, bitmap.Width, bitmap.Height);
System.Drawing.Imaging.BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);
int bufferSize = data.Height * data.Stride;
byte[] bytes = new byte[bufferSize];
System.Runtime.InteropServices.Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
tex.SetData(bytes);
bitmap.UnlockBits(data);
return tex;
}
加载图像行:
backgroundTexture = Tools.GetTexture2DFromBitmap(device, (System.Drawing.Bitmap)System.Drawing.Image.FromFile(@"1.bmp", false));
绘制纹理方法:
spriteBatch.Begin();
Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);
spriteBatch.Draw(backgroundTexture, screenRectangle, Color.White);
spriteBatch.End();
嗯....我认为通过 Texture2D.FromStream 方法加载图像文件更容易......
texture = Texture2D.FromStream(Device, File.OpenRead(path));
是的,它只加载jpg,png和gif图像,但这有什么问题?转换BMP很容易。