How to clear screen when you resize render target?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Diet Estus

I am implementing a “pixel perfect” mode in my resolution manager. When the user toggles through settings, they have the option of toggling from “Fullscreen” mode to “Pixel Perfect” mode.

Fullscreen mode simply calls this:

func set_fullscreen():
	get_tree().set_screen_stretch(SceneTree.STRETCH_MODE_2D,  SceneTree.STRETCH_ASPECT_KEEP, Vector2(640, 360), 1)
	OS.window_fullscreen = true

And Pixel Perfect calls this, which resizes the native resolution to an integer multiple and centers the viewport in the display.

func set_fullscreen_pixel_perfect():

get_tree().set_screen_stretch(SceneTree.STRETCH_MODE_VIEWPORT,  SceneTree.STRETCH_ASPECT_IGNORE, Vector2(640, 360), 1)
	OS.window_fullscreen = true

	var window_size = OS.get_window_size()

	# see how big the window is compared to the viewport size
	# floor it so we only get integers (0, 1, 2, 3 ...)
	var scale_x = floor(window_size.x / viewport.size.x)
	var scale_y = floor(window_size.y / viewport.size.y)

	# use the smaller scale with 1x minimum scale
	var scale = max(1, min(scale_x, scale_y))

	# find the coordinate we will use to center the viewport inside the window
	var diff = window_size - (viewport.size * scale)
	var diffhalf = diff/2 #.floor()

	# attach the viewport to the rect we calculated
	viewport.set_attach_to_screen_rect(Rect2(diffhalf, viewport.size * scale))

This seems to work as intended, except that when the user switches from Fullscreen to Pixel Perfect, the display doesn’t clear, so the previously rendered fullscreen window continues to render in the letterbox margins around the newly rendered viewport.

Looks a bit like this, where ideally the letterbox margins would be black:

enter image description here

Is there a way to force the display to clear when I switch to Pixel Perfect mode so that the margins clear to black?

(I also asked this on Reddit and in Godot Discord, to no avail.)

:bust_in_silhouette: Reply From: caprinae

Can you use the frame_pre_draw signal to paint the entire window black before every frame? I haven’t done this myself but it sounds plausible.