CodeCopy

October 7, 2009

Rotate Zune HD screen to landscape

Filed under: c# — mazzoo @ 22:25
Tags: ,

When developing applications for the Zune HD, you might need to be able to rotate your display to landscape mode. To achieve this easily just make a Pre and Post Draw action ( BeginDraw and EndDraw ), where you manipulate the Viewport. This way you can develop the entire program in horizotal and then rotate it afterwards.

public class LandscapeZuneGame : Game
{
   private RenderTarget2D renderTarget;
   private SpriteBatch spriteBatch;

   public LandscapeZuneGame()
   {
      new GraphicsDeviceManager(this)
      {
         PreferredBackBufferWidth = 480,
         PreferredBackBufferHeight = 272
      };

      IsMouseVisible = true;
   }
   
   protected override void LoadContent()
   {
      renderTarget = new RenderTarget2D(GraphicsDevice, 480, 272, 1, SurfaceFormat.Color);
      spriteBatch = new SpriteBatch(GraphicsDevice);
      base.LoadContent();
   }

   // override BeginDraw so we can set the render target and Viewport before
   // any game drawing occurs.
   protected override bool BeginDraw()
   {
      if (base.BeginDraw())
      {
         GraphicsDevice.SetRenderTarget(0, renderTarget);
         GraphicsDevice.Viewport = new Viewport
         {
            X = 0,
            Y = 0,
            Width = 480,
            Height = 272,
            MinDepth = GraphicsDevice.Viewport.MinDepth,
            MaxDepth = GraphicsDevice.Viewport.MaxDepth
         };
         return true;
      }
      return false;
   }

   // override EndDraw to handle unsetting the render target, resetting the Viewport,
   // and drawing the render target's contents to the screen
   protected override void EndDraw()
   {
      GraphicsDevice.SetRenderTarget(0, null);
      GraphicsDevice.Viewport = new Viewport
      {
         X = 0,
         Y = 0,
         Width = 272,
         Height = 480,
         MinDepth = GraphicsDevice.Viewport.MinDepth,
         MaxDepth = GraphicsDevice.Viewport.MaxDepth
      };

      GraphicsDevice.Clear(Color.Black);
      spriteBatch.Begin();
      spriteBatch.Draw(
         renderTarget.GetTexture(),
         new Vector2(136f, 240f),
         null,
         Color.White,
         MathHelper.PiOver2,
         new Vector2(240f, 136f),
         1f,
         SpriteEffects.None,
         0);

      spriteBatch.End();
      base.EndDraw();
   }
}

Thanks to Nick Gravelyn for the great and easy solution

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.