3

我有一个图像,假设是一个 .png,由用户上传。此图像具有固定尺寸,例如 100x100。

我想用这张图片创建 4 个精灵。

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

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

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

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

我怎样才能用我喜欢的 C# 做到这一点?

提前感谢您的帮助

4

1 回答 1

5

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

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

这是一些示例代码:

// 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();
于 2011-01-25T14:13:56.877 回答