Sunday, October 02, 2016

Pixel perfect mouse click on Images in Android Canvas

I was trying to build a sample for some image manipulation tool. The requirement was that the user should be able to pick an image that he pasted on the screen, move it around, scale and rotate it.

The way we would do this using OpenGL is create a depth buffer use different depth value on each of the Quads' used to render the transparent image. So when you do a readPixel from the depth buffer you will get the z value of the sprite if it was under the touch. This is how we wold distinguish between two overlapping transparent images.

The tracking of z value for different Quads is done automatically in OpenGL when you bind the depth buffer to the current frame buffer and start drawing stuff. Now this i know and have used for a while, but how does this work in the Android Canvas drawing world?

Short answer: in the same way
Long answer: 
These are the steps you should follow to get it done:
  • You have to create a separate Bitmap of the same size as your drawing area
  • Set the Bitmap.Config parameter to Bitmap.Config.A_8
  • Bind a canvas to the buffer. 
  • on Touch event, set the clipping rect of the backbuffer canvas to a rect around the touch location.
  • Read the pixel value from the back buffer bitmap. 
  • Compare the value of pixel to see if it matches any of the sprites. If it does then you have a touch on image else its not.
Following is the function for detecting the pixel value from the backbuffer based on touch location.


This should help you get ahead if you are stuck with the same problem :)



Post a Comment