Thursday, August 5, 2010

Region Handling in Android Canvas

In my previous post I have shared an Image Geo Tagging application for Android. A very important concept of Canvas Region handling was used in that application and thought lets discuss more on that concept. The concept of Region can be used in User Click event handling for any Canvas based drawing and Custom View.

Region is a section of Canvas area- its shape can be rectangular or non rectangular (i.e. circle, triangles, multi-phased polygons etc.). Android provides class, which has a very important and useful method contains(int x, int y);which easily detects whether your click event on the screen falls within the region or not. x and y are the co-ordinate position on the Screen.

How I can use it-
Suppose you have created a custom View and want to do specific operations depending upon which portion of screen user has clicked. Lets explain this with following screen shot-

Above screen is from my application (Image Geo Tagging for Android). Each Pin and its associated image thumbnail popups are part of a single Custom Overlay. Each Custom Overlay instance needs to detect when user has clicked on Pin and Popup, so that it can take appropriate action.

To handle this, we have to define 2 regions-
Region pinRegion = new Region (x1, y1, x1 + pinIcon.getWidth, y1 + pinIcon.getHeight());
Region popupRegion = new Region (x2, y2, x2 + popUpWidth, y2 + popUpHeight);

You need to now overwrite onTouchEvent( MotionEvent e, MapView mapView) method to get user Click events. Get the (x, y) co-ordinates from MotionEvent instance and use the magic function contains(x, y) e.g. pinRegion.contains(x, y) and popupRegion.contains(x, y).

This is really an important concept, if you are planning to control user Click events on specific sections of your Custom View or any Canvas based drawing. For complete code bases please refer my previous post


  1. coule you give your code or give me more explanation, your link isnot opened.

  2. Hi,
    thanks for your comment. I have fixed the link. You can get more details on-

    To get resources from this site pls follow-
    1. Click on the resource link, which will open a new page
    2. Do "Save Link as.." on that new page

    hope this helps.

  3. HI,
    Do you have any idea how to find whether the pixel point is on a bitmap.