display.newImageRect maintaining aspect ratio

display.newImageRect is designed to be flexible with regard to screen dimensions, so that I can specify the rectangle rather than just having the image load at whatever pixel size it is. But I need a slightly different form of flexibility.

My display routine  loads one page at a time for my tutorial. Each page may contain an image, which will be loaded from a file. But not all images have the same aspect ratio. Some are square, some are wider. So here’s what I’d really like to do:

  1. Ascertain the pixel dimensions of my image file.

  2. Calculate a rectangle based on the screen size, the image shape, and my algorithm for “what looks good”.

3. display.newImageRect using that rectangle.

It would also work to load the image and then change its width and height, if that is possible and if I can discern the original image dimensions.

Question 1: Can I do this under the old graphics model? I inherited some legacy code, and I’d really rather not have to convert it to the new graphics model.

Question 2: Is there a better way to do this under the new graphics model?

Thanks,

Ken

You would use display.newImage() and load it in at full size, then compute a scale factor to scale the image by and then use the :scale() method to resize it.

local pic = display.newImage(“someimage.png”)

local  s = 200/pic.width

pic:scale(s, s)

That will make the pic to be 200px wide regardless of height.  If you need to make it fit within a certain height, just divide by height instead of width.

Rob

Just to clarify Rob’s last statement, I normally check if the image width is more than the height or vice versa, and then scale by that dimension:

local s = 1 if image.width \> image.height then s = 200/image.width else s = 200/image.height end img:scale(s, s)

This way you can handle portrait or landscape images at the same time, and confine them to a fixed size.

You would use display.newImage() and load it in at full size, then compute a scale factor to scale the image by and then use the :scale() method to resize it.

local pic = display.newImage(“someimage.png”)

local  s = 200/pic.width

pic:scale(s, s)

That will make the pic to be 200px wide regardless of height.  If you need to make it fit within a certain height, just divide by height instead of width.

Rob

Just to clarify Rob’s last statement, I normally check if the image width is more than the height or vice versa, and then scale by that dimension:

local s = 1 if image.width \> image.height then s = 200/image.width else s = 200/image.height end img:scale(s, s)

This way you can handle portrait or landscape images at the same time, and confine them to a fixed size.