Create an XNA Sprite on the fly with an image

I have an image, let it say .png, which is uploaded by the user. This image has a fixed size of, say, 100x100.

I would like to create 4 sprites with this image.

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

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

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

Last of (50, 50) - (100, 100)

How can I do this with my preferred C #?

Thank you in advance for your help.

+3
source share
1 answer

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

To draw different parts of a texture, use the sourceRectangleoverload option SpriteBatch.Drawthat accepts it ( MSDN ).

Here is a sample 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();
+5
source

Source: https://habr.com/ru/post/1787681/


All Articles