Saturday, April 09, 2011

Why are my textures not showing up on Android?

What a disaster the initial week of "3D Space Game" has been! I recieved lots of 1 star reviews with vague hints about what the problem was - "doesn't work", "goofed up". When I realised there was a problem and added a note on the market asking people to email their problems before "down voting" I got a couple of very helpful bug reports.

It turns out that on the Galaxy S and other larger-screened devices all of the textures I created from PNG images were not showing up. This meant that the control buttons and menu icons just show as white rectangles, completely unusable.

The usual reason for the white rectangle effect is that the size of the texture you're trying to use is not a power of 2. Textures have to be 32x32, 64x32, 128x512, etc - you can't have a 257x123 sized texture (unless it's on the Android emulator, which doesn't care about texture size). I even mentioned this in my "lessons learned" post in January. The code I use creates a texture straight from the PNG like this:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bmp, 0);

The size of the texture is taken from the PNG, which I had carefully made sure was a power of 2. On my HTC Magic the textures show up fine, so I thought everything was working correctly.

Well, it turns out that the BitmapFactory uses a default set of options that includes a "resize" flag. The flag is by default set to true, or "resize the image to screw up Open GL textures", as it should be known. The fix for this was to create my own set of Options and set the flag to false like this:

BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScaled = false;
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
                R.drawable.my_image, opts); /* pass in opts */
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bmp, 0);

Problem solved. Let's hope for a reversal of the 1-star trend, eh readers?

3 comments:

  1. Thanks for fixing it, this issue showed up for my HTC Desire HD.

    ReplyDelete
  2. Nworb2:37 pm

    Thanks for publishing this. I had the same 'white-square' problem on my HTC Desire when testing my code, even though it worked without any problems on my Galaxy Tab 10.1.

    ReplyDelete
  3. Thanks for this suggestion! It fixed up a problem I had spent a whole day trying to track down!

    ReplyDelete

Note: only a member of this blog may post a comment.