如何修改纹理中像素的颜色?

时间:2016-10-24 04:37:10

标签: java libgdx

我通过AssetManager加载了纹理:

AssetManager manager = new AssetManager(...);
manager.load(textureFilepath, Texture.class);
manager.finishLoading();
Texture texture = manager.get(textureFilepath, Texture.class);

我想在运行时修改一些像素颜色。我怎么能这样做?

由于

---更新---------

这是一个测试应用程序,试图改变像素图并不会改变纹理的外观,但是:

public class AppTest extends ApplicationAdapter {

    SpriteBatch batch;
    Texture texture;

    public void create() {
        batch = new SpriteBatch();
        texture = new Texture("foo.jpg");
    }

    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(texture, 100, 100);
        batch.end();
    }

    private void test() {
        TextureData textureData = texture.getTextureData();
        textureData.prepare();
        Pixmap pixmap = textureData.consumePixmap();

        for (int y = 0; y < 200; y++) {
            for (int x = 0; x < 200; x++) {
                pixmap.drawPixel(x, y, 0xff0000ff);
            }
        }
    }

    public boolean touchUp (int screenX, int screenY, int pointer, int button) {
        test();
    }
}

1 个答案:

答案 0 :(得分:1)

短:

pixmap.drawPixel(x, y, color);

首先,您需要从纹理数据中创建一个Pixmap:

TextureData textureData = texture.getTextureData();
textureData.prepare();
Pixmap pixmap = textureData.consumePixmap();

如果你想将红色变成绿色,你需要一个循环并获得rgb888值,因为getPixel会为你返回:

for (int y = 0; y < pixmap.getHeight(); y++) {
  for (int x = 0; x < pixmap.getWidth(); x++) {
      if (pixmap.getPixel(x, y) == Color.rgb888(Color.Red))
      {
        pixmap.drawPixel(x, y, Color.Green);
      }
  }
}

如果您已经知道要更改的内容,则无需循环,只需使用pixmap.drawPixel()

完成Pixmap魔法后,你可以为它创建一个新的纹理。

Texture pixmapTexture = new Texture(pixmap);