getPixel() giving 0 for PNG Bitmap:Android

257 views Asked by At

I am facing this problem for 2 days now. I am making a 2D game via Canvas and it has a PNG file which I am drawing on the canvas by drawBitmap(), and it works fine.

But for Per-Pixel-Collision detection, I am using getPixel(), but it's always returning 0.

I am creating the bitmap in th following way-

Bitmap bmp= BitmapFactory.decodeResource(context.getResources(), R.drawable.image);
//image is a PNG file

but following always gives 0-

Toast.makeText(getContext(),""+bmp.getPixel(x,y), Toast.LENGTH_SHORT).show();
//x and y are within the boundary

I even tried the following, but same results-

BitmapFactory.Options opt=new BitmapFactory.Options();
opt.inMutable=true;
Bitmap bmp= BitmapFactory.decodeResource(context.getResources(), R.drawable.image,opt);

Being a beginner,I don't have much understanding of bitmaps and color scheme, so, reason on why this is happening and any solution would be of great help. My project is stalled midway for this problem.

Thank you

1

There are 1 answers

0
Sucho On

Got a solution on my own. Its rather a workaround, than a solution, but it works.

Just pass a BitmapFactory.Options object to BitmapFactory.decodeStream like the one below.

BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap source = BitmapFactory.decodeStream(context.getResources(), R.image,opt);