11

如何从 TextureRegion 或 Sprite 创建 Pixmap?我需要这个来改变一些像素的颜色,然后从像素图创建新的纹理(在加载屏幕期间)。

4

2 回答 2

21
Texture texture = textureRegion.getTexture();
if (!texture.getTextureData().isPrepared()) {
    texture.getTextureData().prepare();
}
Pixmap pixmap = texture.getTextureData().consumePixmap();

如果您只想要该纹理的一部分(区域),那么您将不得不进行一些手动处理:

for (int x = 0; x < textureRegion.getRegionWidth(); x++) {
    for (int y = 0; y < textureRegion.getRegionHeight(); y++) {
        int colorInt = pixmap.getPixel(textureRegion.getRegionX() + x, textureRegion.getRegionY() + y);
        // you could now draw that color at (x, y) of another pixmap of the size (regionWidth, regionHeight)
    }
}
于 2015-04-04T22:10:05.027 回答
4

如果您不想TextureRegion逐个像素地遍历像素,您也可以将区域绘制到新的Pixmap

public Pixmap extractPixmapFromTextureRegion(TextureRegion textureRegion) {
    TextureData textureData = textureRegion.getTexture().getTextureData()
    if (!textureData.isPrepared()) {
        textureData.prepare();
    }
    Pixmap pixmap = new Pixmap(
            textureRegion.getRegionWidth(),
            textureRegion.getRegionHeight(),
            textureData.getFormat()
    );
    pixmap.drawPixmap(
            textureData.consumePixmap(), // The other Pixmap
            0, // The target x-coordinate (top left corner)
            0, // The target y-coordinate (top left corner)
            textureRegion.getRegionX(), // The source x-coordinate (top left corner)
            textureRegion.getRegionY(), // The source y-coordinate (top left corner)
            textureRegion.getRegionWidth(), // The width of the area from the other Pixmap in pixels
            textureRegion.getRegionHeight() // The height of the area from the other Pixmap in pixels
    );
    return pixmap;
}
于 2019-06-18T17:42:10.803 回答