从图像中动态创建XNA精灵

Tim*_*Tim 3 c# sprite xna-4.0

我有一个图像,让我们说一个.png,由用户上传.此图像具有固定大小,例如100x100.

我想用这个图像创建4个精灵.

一个从(0,0)到(50,50)

另一个从(50,0)到(100,50)

第三个从(0,50)到(50,100)

从(50,50)到(100,100)的最后一个

我如何用我喜欢的C#做到这一点?

在此先感谢您的帮助

And*_*ell 5

要从PNG文件创建纹理,请使用Texture2D.FromStream()方法(MSDN).

要绘制纹理的不同部分,请使用该sourceRectangle参数来SpriteBatch.Draw接受它的重载(MSDN).

这是一些示例代码:

// Presumably in Update or LoadContent:
using(FileStream stream = File.OpenRead("uploaded.png"))
{
    myTexture = Texture2D.FromStream(GraphicsDevice, stream);
}

// In Draw:
spriteBatch.Begin();
spriteBatch.Draw(myTexture, new Vector2(111), new Rectangle( 0,  0, 50, 50), Color.White);
spriteBatch.Draw(myTexture, new Vector2(222), new Rectangle( 0, 50, 50, 50), Color.White);
spriteBatch.Draw(myTexture, new Vector2(333), new Rectangle(50,  0, 50, 50), Color.White);
spriteBatch.Draw(myTexture, new Vector2(444), new Rectangle(50, 50, 50, 50), Color.White);
spriteBatch.End();
Run Code Online (Sandbox Code Playgroud)