I'm trying to resize an image based on the screen height and I'm running into trouble. Currently the problem is that the image simply isn't displaying. Here is the code:
class Board
{
private Texture2D texture;
private int screenWidth = Game1.Instance.GraphicsDevice.Viewport.Width;
private int screenHeight = Game1.Instance.GraphicsDevice.Viewport.Height;
private Vector2 location;
private Rectangle destination;
public Board(Texture2D texture)
{
this.texture = texture;
this.location = new Vector2(200, 0);
this.destination = new Rectangle((int)location.X, (int)location.Y, texture.Width * (screenHeight / texture.Height), screenHeight);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
spriteBatch.Draw(texture,
destination,
Color.White);
spriteBatch.End();
}
}
The image has displayed before, albeit still too wide, so I know that the code within the main loop is fine. So my question in short is... What's wrong with this code and is there a better way to do it?
texture.Width * (screenHeight / texture.Height)
Is using integer division. If the texture is bigger than the screen, it will return 0. With a width of 0, you won't see the texture. Instead, cast one operand to double
or float
:
texture.Width * (screenHeight / (double)texture.Height)
Will return a double
, allowing the division/multiplication to work as you expected.