Iluvpresident
Iluvpresident

Reputation: 175

make a transparent part of an image unclickable

I use Android studio and I have this image with a transparent background. Whenever i click on it it'll bring me to another Activity. But even when I click on the transparent part of the image it'll bring me to the other Activity. Is it possible to make the nontransparent part clickable (or touchable) and the transparent part unclickable?

Upvotes: 1

Views: 1184

Answers (1)

Nick Cardoso
Nick Cardoso

Reputation: 21763

Yes this is possible but it becomes much more difficult than just adding an OnClickListener.

The trick is to use a Touch listener instead of click and on either a DOWN or UP event take the position and then either use some simple maths to work out whether it was a transparent area (if the design is a simple one) or, do some more complicated stuff to work out your pixel values at the centre.

 new View.OnTouchListener() {
     public boolean onTouch(View v, MotionEvent event) {
         If (event.getAction() == MotionEvent.ACTION_DOWN) {
             final int x = (int) event.getX();
             final int y = (int) event.getY();

             //now map the coords we got to the
             //bitmap (because of scaling) 
             ImageView imageView = ((ImageView)v);
             Bitmap bitmap =((BitmapDrawable)imageView.getDrawable()).getBitmap();
             int pixel = bitmap.getPixel(x,y);

             //now check alpha for transparency 
             int alpha = Color.alpha(pixel);
             If (alpha != 0) {
                  //do whatever you would have done for your click event here
             } 
         }
         return true; //we've handled the event
     }
 }

Upvotes: 4

Related Questions