Image scaling (KeepAspectRatioByExpanding) through OpenGL

Simply do the same math you did with KeepAspectRatio, but this time keep the height instead of the width. You’ll get a width bigger than 1, so you’ll have to use the inverse of it for your texture coordinate.


Normalized coordinates yes/no won’t matter, you just have to add these factors for the texture coordinates. For this to work I assume the image fills the whole texture (from (0,0) to (1,1); this makes it easy to multiply the values with your width/height). Texture wrapping has to be off.

Default texture coordinates:

(0,0)-(1,0)
|     |
(0,1)-(1,1)

Aspect ratios:

tex_ar = tex_width / tex_height; // aspect ratio for the texture being used
scr_ar = scr_width / scr_height; // aspect ratio for the quad being drawn

KeepAspectRatio (touch from the inside):

(0, 0)-----------------------(max(1, scr_ar / tex_ar), 0)
|                            |
(0, max(1, tex_ar / scr_ar))-(max(1, scr_ / tex_ar), max(1, tex_ar / scr_ar))

KeepAspectRatioByExpanding (touch from outside; just replace max() with min()):

(0, 0)-----------------------(min(1, scr_ar / tex_ar), 0)
|                            |
(0, min(1, tex_ar / scr_ar))-(min(1, scr_ / tex_ar), min(1, tex_ar / scr_ar))

For your case you’d just have to multiply the resulting texture coordinates with your width/height.

Leave a Comment