Handling the event of touching non-transparent parts of an imageview

466 Views Asked by At

I'm working on my first game app, when user touches an image the app shows a message to the user (or does other things in other situations). My photos are non-geometric shapes (for example animal photos) with 100% transparent backgrounds

like this

(I used Photoshop and saved them in PNG format.)

My problem is that I need it to react (and show the message,...) only when the animal shape itself (NOT the imageview's transparent background/corners) is touched by user.

I used the solution that's offered in this question to find out if the pixel that's touched is transparent or not, but it doesn't work the way I need. Here's part of my onCreate() method in MainActivity.java:

tempIV=(ImageView)findViewById(R.id.birdIV);
final Bitmap bitmap = (BitmapDrawable)tempIV.getDrawable()).getBitmap();
tempIV.setOnTouchListener(new View.OnTouchListener(){
    @Override
    public boolean onTouch(View v, MotionEvent event){
        int x = (int)event.getX();
        int y = (int)event.getY();
        int transparency = bitmap.getPixel(x,y);
        if (transparency == 0)
             { //Do nothing
              return false;}
        else {
                Toast.makeText(MainActivity.this,
                        "This is an animal!", Toast.LENGTH_LONG).show();
              }
            return true;
    }
  });

What should I do?

1

There are 1 best solutions below

1
On

Try using this :-

if (bitmap.getPixel(x, y) == Color.TRANSPARENT)
{
    return false; //don't react
}
else
{
    return true; //do something like intent
}