Android: Creating shaped button

I use a crapload of irregular shaped buttons on my app, and to change the “hot zone” or “clickable area” of the button, I just use the Bitmap.getPixel() method to check for alpha on the image used. If the method returns 0, then don’t perform click event.

Example:
(1) Create your button as usual, whichever way you would like.
(2) Define a Bitmap and assign to it the same image drawable used for the button.
(3) Get the X and Y coordinates of the touch or click action.
(4) Pass the coordinates to the .getPixel(x,y) method.

Sample Code:

// ** Declare your Bitmap somewhere **
final Bitmap TheBitmap;       
TheBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.TheImage);

// ** My onTouch code **
public boolean onTouch(View v, MotionEvent event) {

        int eventPadTouch = event.getAction();

        switch (eventPadTouch) {

            case MotionEvent.ACTION_DOWN:
                if (iX>=0 & iY>=0 & iX<TheBitmap.getWidth() & iY<TheBitmap.getHeight()) { // ** Makes sure that X and Y are not less than 0, and no more than the height and width of the image.                
                    if (TheBitmap.getPixel(iX,iY)!=0) {
                        // * A non-alpha area was clicked, do something 
                    }               
                }
                return true;                
        }           
        return false;
}

The event.getX() and event.getY() simply give you the coordinates of where you touched the button.

** The above sample is to guide you in the correct direction. There are some checks to add to the code to assure no errors occur.

Leave a Comment