XNA和从文件加载图像

时间:2012-04-08 23:10:57

标签: c# image xna loading texture2d

我找到了直接从文件加载图像的方法,但我加载的图像是蓝色(原始是绿色)。我认为它以不好的方式保存,所以我用photoshop保存了它,但没有任何改变。我猜我的程序运行不好。我如何更改它,是从文件加载图像的好方法? 位图到texture2d方法:

    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();

1 个答案:

答案 0 :(得分:2)

嗯....我认为通过Texture2D.FromStream方法加载图像文件更容易......

texture = Texture2D.FromStream(Device,File.OpenRead(path));

是的,它只会加载jpg,png和gif图像,但问题是什么呢? ... 转换bmp很容易..