2011-01-25 79 views
3

我有一个图像,让我们说一个.png,由用户上传。 此图像的大小固定,比如100x100。从图像中动态创建XNA sprite

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

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

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

从(0,50)的第三(50, 100)

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

我如何能做到这一点与我首选C#?

预先感谢任何帮助

回答

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

Texture2D.FromStream非常适合这个,非常感谢 – Tim 2011-01-25 16:55:00