簡體   English   中英

libgdx - 將多個紋理合並為一個

[英]libgdx - combine a number of textures into one

有沒有辦法使用 libgdx API 將多個紋理組合成一個紋理?

例如,考慮擁有這 3 個紋理:

Texture texture1 = new Texture("texture1.png");
Texture texture2 = new Texture("texture2.png");
Texture texture3 = new Texture("texture3.png");

目標是將它們組合成一個可用的紋理,有沒有辦法做到?

我想得到相同的結果,但我沒有發現之前給出的說明有任何幫助。 對於這個問題,我也找不到任何其他明確的解決方案,所以這是我在閱讀了一些 api-docs 並自己進行了一些測試后設法開始工作的方法。

Texture splashTexture = new Texture("texture1.png"); // Remember to dispose
splashTexture.getTextureData().prepare(); // The api-doc says this is needed
Pixmap splashpixmap = splashTexture.getTextureData().consumePixmap(); // Strange name, but gives the pixmap of the texture. Remember to dispose this also
Pixmap pixmap = new Pixmap(splashTexture.getWidth(), splashTexture.getHeight(), Format.RGBA8888); // Remember to dispose
// We want the center point coordinates of the image region as the circle origo is at the center and drawn by the radius
int x = (int) (splashTexture.getWidth() / 2f);
int y = (int) (splashTexture.getHeight() / 2f);
int radius = (int) (splashTexture.getWidth() / 2f - 5); // -5 just to leave a small margin in my picture
pixmap.setColor(Color.ORANGE);
pixmap.fillCircle(x, y, radius);
// Draws the texture on the background shape (orange circle)
pixmap.drawPixmap(splashpixmap, 0, 0);
// TADA! New combined texture
this.splashImage = new Texture(pixmap); // Not sure if needed, but may be needed to get disposed as well when it's no longer needed
// These are not needed anymore
pixmap.dispose();
splashpixmap.dispose();
splashTexture.dispose();

然后使用 splashImage (在我的例子中是 Texture 類型的類變量)在您想要的位置渲染組合圖像。 生成的圖像具有給定的背景,前景是一個 png 圖像,它具有要由背景顏色填充的透明部分。

@Ville Myrskyneva 的回答有效,但它並沒有完全展示如何組合 2 個或更多紋理。 我制作了一個 Utility 方法,它將 2 個紋理作為輸入並返回一個組合紋理。 請注意,第二個紋理將始終繪制在第一個紋理的頂部。

public static Texture combineTextures(Texture texture1, Texture texture2) {
    texture1.getTextureData().prepare();
    Pixmap pixmap1 = texture1.getTextureData().consumePixmap();

    texture2.getTextureData().prepare();
    Pixmap pixmap2 = texture2.getTextureData().consumePixmap();

    pixmap1.drawPixmap(pixmap2, 0, 0);
    Texture textureResult = new Texture(pixmap1);

    pixmap1.dispose();
    pixmap2.dispose();

    return textureResult;
}

您應該使用 TexturePacker 從許多小紋理中創建一個大紋理。 https://github.com/libgdx/libgdx/wiki/Texture-packer

這是 GUI 版本 (jar),它將幫助您在將所有紋理打包到您的項目之前將它們打包成一個: https://code.google.com/p/libgdx-texturepacker-gui/

您還應該記住,對於大多數 Android 和 IOS 設備,一種紋理的最大尺寸是: 2048x2048

如果您想使用組合紋理作為圖集以提高性能,最好使用 @Alon Zilberman 答案。

但我認為你的問題是關於另一個問題。 如果您想從這三個紋理中獲取一些自定義紋理(例如通過一張一張地繪制它們來合並它們),那么您最好的解決方案是繪制到 FrameBuffer。 在這里你可以找到如何做到這一點的好例子https://stackoverflow.com/a/7632680/3802890

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM