The Complete Sample
The code in this topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.
Drawing a Sprite
To draw a sprite on screen
-
Derive a class from Game.
-
Define a SpriteBatch object as a field on your game class.
-
In your LoadContent method, construct the SpriteBatch object, passing the current graphics device.
-
Load the textures that will be used for drawing sprites in LoadContent.
In this case, the example uses the Content member to load a texture from the XNA Framework Content Pipeline. The texture must be in the project, with the same name passed to Load.
C#private Texture2D SpriteTexture; private SpriteBatch ForegroundBatch; private Rectangle TitleSafe; protected override void LoadGraphicsContent( bool loadAllContent ) { if (loadAllContent) { ForegroundBatch = new SpriteBatch( graphics.GraphicsDevice ); SpriteTexture = content.Load<Texture2D>( "Sprite" ); } TitleSafe = GetTitleSafeArea( .8f ); }
-
After Clear, call Begin on your SpriteBatch object.
-
Create a Vector2 to represent the screen position of the sprite.
On Xbox 360, be careful not to draw foreground sprites on the outer 10 or 20 percent of the screen. Some televisions may obscure the edge of the screen. The GetTitleSafeArea function calculates the area of the current Viewport that is safe, given a specified safety percentage.
C#protected Rectangle GetTitleSafeArea( float percent ) { Rectangle retval = new Rectangle( graphics.GraphicsDevice.Viewport.X, graphics.GraphicsDevice.Viewport.Y, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height ); #if XBOX // Find Title Safe area of Xbox 360. float border = (1 - percent) / 2; retval.X = (int)(border * retval.Width); retval.Y = (int)(border * retval.Height); retval.Width = (int)(percent * retval.Width); retval.Height = (int)(percent * retval.Height); return retval; #else return retval; #endif } 这里计算了显示屏幕的范围,因为有些屏幕的边缘部分是不能显示的。经验阿~
-
Call Draw on your SpriteBatch object, passing the texture to draw, the screen position, and the color to apply.
-
Use Color.White to draw the texture without any color effects.
-
When all the sprites have been drawn, call End on your SpriteBatch object.
C#protected override void Draw( GameTime gameTime ) { graphics.GraphicsDevice.Clear( Color.CornflowerBlue ); ForegroundBatch.Begin(); Vector2 pos = new Vector2( TitleSafe.Left, TitleSafe.Top ); ForegroundBatch.Draw( SpriteTexture, pos, Color.White ); ForegroundBatch.End(); base.Draw( gameTime ); }