mardi 4 avril 2017

Java (Android) - BitmapFactory for loop Vs if Statement?

I have a game written in Java for an Android device where a bitmap is displayed as a life (total of 3 lives).

The following code implementation displays 3 hearts and when a life is lost one of the hearts is removed from the display:

Bitmap lifebmp = BitmapFactory.decodeResource(getResources(), R.drawable.alife);

if(lives > 0){
    canvas.drawBitmap(lifebmp, 10, 10, paint);
    if(lives > 1){
        canvas.drawBitmap(lifebmp, 100, 10, paint);
        if(lives > 2){
            canvas.drawBitmap(lifebmp, 190, 10, paint);
        }
    }
}

I've competed a lot of the View for this Activity and have been identifying and changing code where I realise it can be made more efficient. When I got to the if statement above I thought a for loop would do the trick just as well and changed the if statement to a for loop which now looks like this:

Bitmap lifebmp = BitmapFactory.decodeResource(getResources(), R.drawable.alife);

for(int i = 0;i < lives;i++){
    canvas.drawBitmap(lifebmp, (10 + ((lives - 1) * 90)), 10, paint);
}

The problem I have is that only the last iteration of the life is displayed when I run the game. When a life is lost that heart disappears and then only the second heart is displayed (basically only one bitmap is displayed at a time).

In my head this should work, however if anyone can shine a light on this or suggest another way of making this code more efficient then it would be much appreciated. Thank you.

(I've also tried a while loop - same result)

Aucun commentaire:

Enregistrer un commentaire