How to create an irregular shaped imagebutton where transparent part of image is not clickable?
Asked Answered
M

1

5

I have an irregular shaped PNG image for example a round image where the corners are transparent.

How can I create an imagebutton of this image and not letting the corners being touchable?

If possible I may want to create other irregular shaped imagebuttons.

Mab answered 22/11, 2011 at 9:51 Comment(0)
L
5

Check out the second answer to this question, I believe it's exactly what you need.

Later edit:

Quick summary:

  1. Use a TouchListener instead of ClickListener

  2. Inside the listener, if the event is MotionEvent.ACTION_DOWN, get the touch coordinates

  3. Check the image's pixel at the coordinates you obtained earlier; if the pixel is not transparent, consider the button was clicked, otherwise ignore the event.

Lunation answered 22/11, 2011 at 10:0 Comment(10)
By changing the "hot zone" or "clickable area" method? Let me try and see. Thanks mate.Mab
Elaborate on this, please. "Couldn't get it work" could mean anything. The answer I pointed you to seems pretty straightforward.Lunation
Sorry still new in Android, I'm not exactly sure how to use that snippet into my code. Currently I have an ImageButton listening an onClickEvent. How does that onTouch or MotionEvent fill in?Mab
Yes I'm able to get the touched coordinates. How do I check whether the coordinates are belonged to which image? And how do I check the transparency using the pixel? The getPixels() method is for Bitmap. Perhaps I need to draw the buttons using Bitmap?Mab
Get the bitmap by using Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.YOUR_IMAGE_ID);. Now you have the bitmap object and you can use getPixel to check for transparency.Lunation
Using Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.id.myimageid); I get a null point exception for getPixelMab
If using Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.myimagename); I get java.lang.OutOfMemoryError: bitmap size exceeds VM budgetMab
Now I'm able to getPixel from the image. My image is a round shaped image with corners of the image being transparent. But I'm still getting a touch event on the corners(transparent) part of the image.Mab
If the pixel is non-transparent it means the touch is valid; you have to do your processing here and return true.Lunation
Yes I got it working with another image below it! Thanks a lot Gabriel :)Mab

© 2022 - 2024 — McMap. All rights reserved.