动态更新像素图的充分方法是什么?

What is the sufficient way of updating a pixmap dynamically?

目标

目前我正在使用 libgdx Pixmap 创建一个健康栏,但是当我将 drawLine 参数更改为新值时突然仍然没有任何变化。下面的代码是我当前的工作代码,我不确定这是否是动态绘制 Pixmap 的充分方法。

// This code is working when written all in update method

Pixmap frame = new Pixmap(32, 3, Pixmap.Format.RGBA8888);
frame.drawRectangle(...);
frame.drawLine(...);

Texture texture = new Texture(frame);
frame.dispose();

batch.begin();
batch.draw(texture ...);
batch.end();

示例健康栏

你不应该为此使用 Pixmap(根据一般经验法则:如果你认为你需要为某些事情使用 Pixmap 那么你很可能是错误的)。 Pixmap 用于加载、存储或操作 CPU 内存中的图像数据:RAM。在 CPU 内存中操作图像数据相对较慢,并且生成的数据不能用于在屏幕上渲染,例如SpriteBatch.

为此,您需要将数据从 CPU 内存上传(复制)到 GPU 内存:VRAM。一个Texture用来表示VRAM中的图像数据。所以,实际上,您可以通过从中创建一个 Texture 来做到这一点。或者,您可以通过调用 texture.load(pixmap) 方法来重用现有纹理。但是从RAM上传图像数据到VRAM也比较慢。

因此,与其在 CPU 上操作图像数据然后将其复制到 GPU,不如直接使用 GPU 来实现您想要的效果。您没有提供足够的信息来说明您实际想要实现的目标,但这里有一些选项可以帮助您入门。

  1. 只绘制整个条形图的一部分。假设您的地图集中有一张图像代表完整的健康状况,您只想渲染它的一部分,代表实际健康状况:batch.draw(region.getTexture(), x, y, width * health, height, region.getU(), region.getV(), region.getU() + health * (region.getU2() - region.getU()), region.getV2());(此处为 xywidthheight 是世界坐标中条的位置和大小,health 是范围从 0 到 1 的标准化健康值。
  2. TextureRegion 缩放到栏的大小。假设您的健康栏完全不透明或只有外线,那么您可以使用单个像素 TextureRegion 并将其缩放为您想要的大小:barch.draw(region, x, y, width * health, height);
  3. 使用 nine-patch.
  4. 使用 ShapeRenderer,它提供与 Pixmap 几乎相同且更多的绘图功能,但它直接使用 GPU 来完成。