1

I'm making a simple 2D game for android using Bitmap sprites on a SurfaceView.

From this example, I'm able to load a bitmap and set the black pixels to transparent.

This renders fine and the formerly black pixels are transparent, however if I apply any rotation to the canvas before rendering the bitmap, the transparency is lost and the black pixels are opaquely rendered.

Some code...

In class definition:

private Paint paintSprite;
private Bitmap playerSprite;

In constructor:

paintSprite = new Paint();

BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;

playerSprite = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.asx27, options);

//Make black parts of the bitmap transparent.
for(int x = 0; x < playerSprite.getWidth(); x++)
{
    for(int y = 0; y < playerSprite.getHeight(); y++)
    {
        if(playerSprite.getPixel(x, y) == Color.BLACK)
        {
            playerSprite.setPixel(x, y, Color.TRANSPARENT);
        }
    }
}

In render function:

canvas.save();
canvas.translate(player.GetX() + playerSprite.getWidth() / 2, player.GetY() + playerSprite.getHeight() / 2);
canvas.rotate(player.GetPitch());
canvas.scale(1.0f, -1.0f);
canvas.drawBitmap(playerSprite, -playerSprite.getWidth() / 2, -playerSprite.getHeight() / 2, paintSprite);
canvas.restore();

Can anyone offer an explanation and/or solution?

Community
  • 1
  • 1
Toby Wilson
  • 1,467
  • 5
  • 19
  • 42
  • Is it just the rotation? i.e. if you comment out `canvas.rotate` but keep the translate and scale, the pixels are transparent? – fadden May 02 '15 at 15:20
  • 1
    What version of Android? Does the behavior change if you enable/disable hardware acceleration? http://developer.android.com/guide/topics/graphics/hardware-accel.html – fadden May 02 '15 at 22:52
  • Interestingly, in my render routine, canvas.isHardwareAccelerated() is returning false, whether I specify hardware acceleration in the manifest or not. Test phone is a Huawei Ascend Mate which I'd be very suprised if it lacked appropriate graphics hardware; how common (or cheap) are Android phones that don't support it? Using API level 15 FYI. – Toby Wilson May 04 '15 at 21:31
  • Canvas on SurfaceView is never hardware-accelerated, so the result is expected. (Somehow the fact that this was on a SurfaceView fell out of my brain before I asked the follow-up question.) At any rate, I'm at a loss to understand why applying a rotation would affect the blend function. – fadden May 04 '15 at 21:37
  • Conclusion is, from all information I can find, SurfaceViews are not ('correctly') hardware accelerated. As you say, this doesn't explain the transparency issue, but is as good a reason as any to knob it off and use OpenGL instead (which isn't proving to be drastically painful). – Toby Wilson May 09 '15 at 23:26

0 Answers0