【Godot】自定义预览场景图片,居中显示场景图片

Godot 4.0 stable

##  预览场景图片
##[br]
##[br][code]scene[/code]  预览的场景。这个场景在渲染的时候会添加到场景中,请确保这个场景加载不是很慢的速度
##[br][code]callback[/code]  回调方法,需要一个 [ImageTexture] 参数接收渲染后的图片
static func preview_scene(scene: PackedScene, callback: Callable) -> void:
	# 视图节点
	var viewport = SubViewport.new()
	viewport.name = "__preview_vieport_%s" % [viewport.get_instance_id()]
	viewport.render_target_update_mode = SubViewport.UPDATE_ALWAYS
	viewport.canvas_item_default_texture_filter = Viewport.DEFAULT_CANVAS_ITEM_TEXTURE_FILTER_NEAREST
	viewport.transparent_bg = true
	viewport.size = Engine.get_main_loop().root.size
	
	var instance = scene.instantiate(PackedScene.GEN_EDIT_STATE_INSTANCE)
	viewport.add_child(instance)
	if instance is CanvasItem:
		instance.position = Engine.get_main_loop().root.size / 2
	Engine.get_main_loop().root.add_child(viewport)
	
	# 视图显示 Texture2D
	var viewport_texture = ViewportTexture.new()
	viewport_texture.viewport_path = viewport.get_path_to(Engine.get_main_loop().root)
	RenderingServer.frame_post_draw.connect(func():
		# 渲染后进行图像回调
		var image : Image = viewport.get_texture().get_image()
		if image.is_empty():
			image = Image.create(1, 1, false, Image.FORMAT_BPTC_RGBA)
		else:
			image = image.get_region(image.get_used_rect())
		callback.call(ImageTexture.create_from_image(image))
		viewport.queue_free()
	, Object.CONNECT_ONE_SHOT)

你可能感兴趣的:(Godot,godot,游戏引擎,gdscript)