如何绘制精灵

在屏幕上绘制精灵

  1. 创建一个Game类的派生类。

  2. 在游戏类中定义一个SpriteBatch对象实例。

  3. 在你的LoadContent方法中实例化一个SpriteBatch对象,实例化他的时候需要将当前的图形设备类--GraphicsDevice类的实例作为参数传递给他的构造函数。

  4. 在LoadContent中加载绘制精灵时要用到的纹理。

    此例中使用Content 成员从XNA框架素材管道中加载一个纹理。纹理必须要存在于工程中,而且要和传递给Load的名字相同。

    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 );
    }
  5. 在重载的Draw方法中调用Clear。

  6. 调用Clear之后,调用SpriteBatch对象的Begin方法。

  7. 创建一个Vector2变量来储存精灵的屏幕位置 。

    在Xbox 360平台上,注意不要将前景的精灵绘制超过屏幕边缘百分之10至20的区域,因为有些电视机会遮盖屏幕的边缘。GetTitleSafeArea函数根据给定的安全百分比计算当前Viewport安全区域。

        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
        }
  8. 调用SpriteBatch对象的Draw方法,将要绘制的纹理,屏幕位置和颜色作为参数传递给他。

  9. Color.White表示绘制没有任何颜色效果的纹理。

  10. 绘制完所有的图形对象后, 调用SpriteBatch对象的End方法。

    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 );
    }

发布时间:2009/2/11 7:53:55  阅读次数:8063

2006 - 2024,推荐分辨率1024*768以上,推荐浏览器Chrome、Edge等现代浏览器,截止2021年12月5日的访问次数:1872万9823 站长邮箱

沪ICP备18037240号-1

沪公网安备 31011002002865号