0

Just to add a surprise factor to my game, I have decided to invert the background colors randomly. When the player collects, let's say, 21 golden bacon strips the background changes. By modifying the bitmap's pixels, I have done this through the following code:

public void invert() {
    int length = BackBitmap.getWidth() * BackBitmap.getHeight();
    int[] array = new int[length];
    BackBitmap.getPixels(array, 0, BackBitmap.getWidth(), 0, 0, BackBitmap.getWidth(), BackBitmap.getHeight());
    int[] array2 = new int[length];
    int a2 = 0;

    for(int col = 0; col < BackBitmap.getHeight(); col++){
        for (int row = 0; row < BackBitmap.getWidth();row++){
            array2[a2] = BackBitmap.getPixel(row,col);
            a2++;
        }
    }

    for (int i=0;i<length;i++){
        array[i] = 0xFFFFFF - array2[i];
        }
    BackBitmap = BackBitmap.copy(Bitmap.Config.ARGB_8888, true);
    BackBitmap.setPixels(array, 0, BackBitmap.getWidth(), 0, 0, BackBitmap.getWidth(), BackBitmap.getHeight());
}

However once the colors are inverted, the game encounters major lag. To my surprise I thought this way of updating bitmap would be the most effective - memory-wise. What would be the right way to approach this error?

1 Answers1

0
public void invert() {
    int length = BackBitmap.getWidth() * BackBitmap.getHeight();
    int[] array = new int[length];
    int[] array2 = new int[length];
    BackBitmap.getPixels(array2, 0, BackBitmap.getWidth(), 0, 0, BackBitmap.getWidth(), BackBitmap.getHeight());

    for (int i=0;i<length;i++){
        array[i] = 0xFFFFFF - array2[i];
    }
    BackBitmap = BackBitmap.copy(Bitmap.Config.ARGB_8888, true);
    BackBitmap.setPixels(array, 0, BackBitmap.getWidth(), 0, 0, BackBitmap.getWidth(), BackBitmap.getHeight());
}

This is how I would write it. You were writing to array and then rewriting it without using it.

This may not reduce lag significantly but it may help to a degree.

CraigR8806
  • 1,584
  • 13
  • 21