SoluableNonagon
SoluableNonagon

Reputation: 11752

zoom an image to fit a screen horizontally - algorithm

This is a general question regarding an algorithm to zoom an image to fit the width of a screen, there are some givens and some constraints. We can assume we are using Java but this question is more mathematical that language dependent.

First of all, the image loads and fits into the dimensions of the screen vertically first, not horizontally.

initial

We can get the dimensions of the screen and the dimensions of the image with methods, but we cannot set the dimensions of either (We only have getters not setters).

imageWidth = image.getWidth(); //integer
imageHeight = image.getHeight(); //integer
screenWidth = screen.getWidth(); //integer
screenHeight = screen.getHeight(); //integer

The only method to resize the image is by setting scale (zooming essentially).

image.setScale(some float); // optionally image.setZoom(integer);

What I would like to know is how to calculate the scale (zoom) level for some l x h image so that it fits a L x H screen horizontally?

second

Upvotes: 1

Views: 618

Answers (1)

niklasfi
niklasfi

Reputation: 15961

All you have to do to make the Image fill your screen is scale along the x axis:

scaling_factor = screen.getWidth()/image.getWidth()
image.setScale(zoom_factor);

The formula is very intuitive:

  • The image height is irrelevant. The scaling you desire would be the same for a landscape and vertical image, as long as the width of both images are the same
  • When the image's width increases, your scaling factor decreases
  • When your screen size increses, the scaling factor increases.

Upvotes: 2

Related Questions