I have a project were the background is stretching to fill the viewport but it's keeping it's aspect ratio and centering it, thereby. I had a problem getting the actual area of where it was painting the texture. Needed it to know where to paint the rest of the playing field.
Is there a better solution than what I did below?
I used Expand on and StretchMode KeepAspectCentered in the editor settings for the TextureRect
I was expecting to be able to extract the coordinates somehow from the TextureRect but wasn't able to.
My solution was making a function to calculate it in code. Maybe not the most elegant, but it works. If you use this, remember that it expects the TextureRect to be centered as well, if you use some other Keep aspect you need to change the calculations in the function. Maybe it's useful to someone, maybe you have a suggestion how to improve it, but here is my quick and dirty take on it:
#takes a TextureRect and calculates the actual textured rectangle after scaling and centering has been done
#returns a Rect2.
#Use this function in _on_XXXX_changed(): for the TextureRect
#Example:
#func _on_MyTexture_changed():
# var as_rect = get_aspect_rect($MyTexture)
func get_aspect_rect(t:TextureRect):
var aspect_rect:Rect2
var aspect_diffx_pos = 0
var aspect_diffy_pos = 0
var aspect_diffx_size = t.rect_size.x
var aspect_diffy_size = t.rect_size.y
var t_aspect:float
var t_new_aspect:float = t.rect_size.x / t.rect_size.y
t_aspect = convert(t.texture.get_width(),TYPE_REAL)/convert(t.texture.get_height(),TYPE_REAL)
if(t_new_aspect>t_aspect):
aspect_diffx_pos = t.rect_size.x-(t.rect_size.y*t_aspect)
aspect_diffx_size = t.rect_size.x - aspect_diffx_pos
aspect_diffx_pos = aspect_diffx_pos/2
else:
aspect_diffy_pos = t.rect_size.y-(t.rect_size.x/t_aspect)
aspect_diffy_size = t.rect_size.y - aspect_diffy_pos
aspect_diffy_pos = aspect_diffy_pos/2
aspect_rect.position.x = aspect_diffx_pos
aspect_rect.position.y = aspect_diffy_pos
aspect_rect.size.x = aspect_diffx_size
aspect_rect.size.y = aspect_diffy_size
return aspect_rect