2011-09-21 19 views

回答

1

在XNA這不是一般的最有效的事情,但我認爲最好的方法是可能創建紋理並使用SetData設置每個像素,並使用SpriteBatch將其渲染到屏幕上。

SpriteBatch spriteBatch; 
    Texture2D t; 
    Color[] blankScreen; 

    protected override void LoadContent() 
    { 
     spriteBatch = new SpriteBatch(GraphicsDevice); 

     //initialize texture 
     t = new Texture2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, false, SurfaceFormat.Color); 

     //clear screen initially 
     blankScreen = new Color[GraphicsDevice.Viewport.Width * GraphicsDevice.Viewport.Height]; 
     for (int i = 0; i < blankScreen.Length; i++) 
     { 
      blankScreen[i] = Color.Black; 
     } 

     ClearScreen(); 
    } 

    private void Set(int x, int y, Color c) 
    { 
     Color[] cArray = { c }; 

     //unset texture from device 
     GraphicsDevice.Textures[0] = null; 
     t.SetData<Color>(0, new Rectangle(x, y, 1, 1), cArray, 0, 1); 

     //reset 
     GraphicsDevice.Textures[0] = t; 
    } 

    private void ClearScreen() 
    { 
     //unset texture from device 
     GraphicsDevice.Textures[0] = null; 
     t.SetData<Color>(blankScreen); 

     //reset 
     GraphicsDevice.Textures[0] = t; 
    } 

    protected override void Draw(GameTime gameTime) 
    { 
     spriteBatch.Begin(); 
     spriteBatch.Draw(t, Vector2.Zero, Color.White); 
     spriteBatch.End(); 

     base.Draw(gameTime); 
    } 

有了這個功能,您可以在更新或繪圖中隨時調用Set或ClearScreen。您可能需要使用紋理索引(我在本例中只使用了0,可能不適合您),並且您只需要每幀取消一次/復位一次,以便根據您的使用方式進行優化他們。