Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
ImageTexture
繼承: Texture2D < Texture < Resource < RefCounted < Object
說明
基於 Image 的 Texture2D。若要顯示影像,必須使用 create_from_image() 方法從中建立一個 ImageTexture:
var image = Image.load_from_file("res://icon.svg")
var texture = ImageTexture.create_from_image(image)
$Sprite2D.texture = texture
如此一來,便可通過載入編輯器內外部的影像,在執行時動態建立紋理。
警告:最好使用 @GDScript.load() 載入匯入的紋理,而不是使用 Image.load() 從檔案系統中動態載入它們,因為後者可能不適用於匯出的專案:
var texture = load("res://icon.svg")
$Sprite2D.texture = texture
這是因為影像必須首先作為 CompressedTexture2D 被匯入,然後才能被 @GDScript.load() 載入。若仍希望像載入其他 Resource 一樣載入影像檔案,可先將其作為 Image 資源匯入,然後使用 @GDScript.load() 方法正常載入。
注意:若要從已匯入的紋理中重新獲得影像,可以使用 Texture2D.get_image(),該方法回傳影像的副本:
var texture = load("res://icon.svg")
var image = texture.get_image()
ImageTexture 並非設計為在編輯器介面內直接操作,其主要用途是通過程式碼在螢幕上動態渲染影像。如果你需要在編輯器內部程式化生成影像,請考慮將其儲存並匯入為自訂紋理資源,這需要實作一個新的 EditorImportPlugin。
注意:由於圖形硬體限制,最大紋理大小為 16384×16384 像素。
教學
屬性
resource_local_to_scene |
|
方法
create_from_image(image: Image) static |
|
void |
|
void |
set_size_override(size: Vector2i) |
void |
方法說明
ImageTexture create_from_image(image: Image) static 🔗
建立一個新的 ImageTexture,並通過分配和設定來自 Image 的資料來初始化它。
void set_image(image: Image) 🔗
用新的 Image 替換該紋理的資料。這將為該紋理重新分配新記憶體。
如果要更新影像,但不需要更改其參數(格式、大小),請改用 update() 以獲得更好的效能。
void set_size_override(size: Vector2i) 🔗
將紋理的大小調整為指定的尺寸。
用新的 Image 替換該紋理的資料。
注意:該紋理必須使用 create_from_image() 建立、或首先使用 set_image() 方法初始化,然後才能更新。新的影像大小、格式和 mipmaps 配置,應與現有紋理的影像配置相配對。
如果需要頻繁更新紋理,請使用該方法而不是 set_image(),這比每次為一個新紋理分配額外記憶體要快。