开发者

Create XNA sprite on the fly from an image

I have an image, let's says a .png, that is uploaded by the user. This image has a 开发者_开发问答fixed size, let's say 100x100.

I would like to create 4 sprites with this image.

One from (0,0) to (50,50)

Another from (50, 0) to (100, 50)

The third from (0, 50) to (50, 100)

The last from (50, 50) to (100, 100)

How can I do that with my prefered C# ?

Thanks in advance for any help


To create a texture from a PNG file, use the Texture2D.FromStream() method (MSDN).

To draw the different sections of the texture, use the sourceRectangle parameter to an overload of SpriteBatch.Draw that accepts it (MSDN).

Here's some example code:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜