Search code examples
javalibgdx

LibGDX fastest way to render color array


I have a color array. When I use ShapeRenderer it takes to much time. I use this code:

for (int i = 0; i < colors.length; i++) {
        for (int j = 0; j < colors[0].length; j++) {
            shapeRenderer.setColor(colors[i][j]);
            shapeRenderer.rect(i,j,1,1)
        }
    }

There must be a faster way because Textures are made from pixels to and their rendering is really fast. My question is: How can I render this color array as fast as a texture?


Solution

  • Textures are drawn really fast because it's generally only a few calls to the GPU. Doing this pixel by pixel requires many many more calls and state changes. There isn't much you can do to change that if the array gets changed often. If it doesn't, you should draw them onto a texture when they are changed, and then just use the texture.

    In LibGDX, you can draw each pixel onto a Pixmap and then create a new texture from that. Source: https://github.com/libgdx/libgdx/wiki/Pixmaps

    Sample Code:

    Pixmap pixmap = new Pixmap( colors.length, colors[0].length, Format.RGBA8888 );
    for (int i = 0; i < colors.length; i++)
    {
        for (int i = 0; i < colors.length; i++)
        {
    
            pixmap.setColor( 0, 1, 0, 0.75f ); //Set to color r,g,b,a
            pixmap.drawPixel(i,j); //Draw the pixel
        }
    }
    Texture pixmaptex = new Texture(pixmap); //Create new texture from the Pixmap
    pixmap.dispose();