Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to get a sprite to position itself at the center of the screen but nothing seems to be working for me. I'm trying

Viewport viewport = graphics.GraphicsDevice.Viewport;
logoPosition = new Vector2((viewport.Width - towerImage.Width) / 2,
                           (viewport.Height - towerImage.Height) / 2);


spriteBatch.Draw(towerImage, centre, null, Color.White, 0, baseOrigin, 1.0f, SpriteEffects.None, 0);

This is my first time using XNA and I don't really have a clue what I'm doing.

share|improve this question
up vote 2 down vote accepted

Unless you pasted your example wrong, you're not even using the logoPosition you calculated when drawing, and you're not showing what the contents of centreand baseOriginare, so it's hard to tell you where the problem is.

But anyway I'd use the position and origin parameters of SpriteBatch.Draw in order to draw the image centered. In two steps, although you could inline:

  1. Calculate the center of the screen and the center of the image:

    Vector2 screenCenter = new Vector2(viewport.Width / 2f, viewport.Height / 2f);
    Vector2 imageCenter = new Vector2(towerImage.Width / 2f, towerImage.Height / 2f);
  2. Use the center of the screen as the position and the center of the image as the origin:

                                 // position                          // origin
    spriteBatch.Draw(towerImage, screenCenter, null, Color.White, 0f, imageCenter, 1f, SpriteEffects.None, 0f);
share|improve this answer

I've never used XNA for a windows phone but I already can tell what your problem is. You aren't following order of operations. Try this:

Viewport viewport = graphics.GraphicsDevice.Viewport;
logoPosition = new Vector2(viewport.Width - towerImage.Width / 2,
                           viewport.Height - towerImage.Height / 2);

You must divide the second height/width before you subtract if from the original. Otherwise it just negates itself and then divides 0 by 2.

share|improve this answer
You must have misunderstood some part, since what he was doing is essentially the same as viewportSize/2 - imageSize/2 which is correct. In other words, it calculates the center of the screen, and then subtracts half of the size of the image in order to center it there. Also, the thing about the negation would only happen if viewport and towerImage had the same size, which is unlikely, and even in that case, the result is correct (i.e. 0/2 = 0). – David Gouveia May 31 '12 at 1:10

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.