Godot Version
v4.3.stable.official [77dcf97d8]
Issue
How do I scale an image of arbitrary size (only known at runtime) to fit into the main window of the app (also, size only known at runtime)?
Scenario
I’m trying to make a slide show. The user opens the directory, I recursively scan it to look for image files and then display a new image whenever a timer fires. That’s all working except that the images are not scaled to fit in the window. I use get_window().size
to determine the window’s size. This value seems reasonable (5120 x 2824 on an 27" 5K iMac).
Question
How do I actually scale the image?
I tried:
var win_size = get_window().size
img.resize( win_size.x, win_size.y )
Printing the new img.size
shows that it has been resized, but when I display it, it still shows the image too large. I display as follows:
output_texture.texture = ImageTexture.create_from_image( img )
Where output_texture
is a TextureRect
configured to fill the root node of the scene which is a canvas layer.
Scene layout is:
CanvasLayer
|- FileDialog
|- Timer
|- TextureRect (called output_texture in the code)
Full Image Load and Display Code
func _on_timer_timeout() -> void:
if current_file_idx > files_to_show.size():
timer.stop()
directory_dialog.popup()
else:
var fn : String = ""
var img : Image = null
while not img :
fn = files_to_show[ current_file_idx ]
current_file_idx += 1
img = Image.load_from_file( fn )
if not img:
print( "[", fn, "] !! failed" )
var height : int = img.get_height()
var width : int = img.get_width()
img.resize( window.size.x, window.size.y )
var txtscale : float = min( float(window.size.y) / float(height), float(window.size.x) / float(width) )
var txt : ImageTexture = ImageTexture.create_from_image( img )
print( "[", fn, "] ( ", width, ", ", height, " ) * ", txtscale, " - Display: ", window.size )
output_texture.texture = txt
Output
No files have printed the “!! failed” message.
The output printed for a particular file:
[Camouflaged Masala.png] ( 1108, 1478 ) * 1.9106901217862 - Display: (5120, 2824)
Image Details for the file (note, file is smaller than screen):
What the program displays (cropped):
As you can see, even though the image is smaller than the window, it is scaled to be much larger (and also, offset).