Suppose i have drawn a bitmap image or simple circle on my canvas. How can i set OnTouchListener to check if my drawing has been touched? Since i will be drawing multiple circles on the canvas, I want each one of them to have some unique id so i can work accordingly.
Asked
Active
Viewed 2,375 times
3
-
Your view has a onTouch(..) which can be used for touch events on the screen – Raghunandan Mar 14 '13 at 15:34
-
but then how can i specifically know which one of circles on the canvas are touched? – Mach Mitch Mar 14 '13 at 15:36
-
calculate the distance between center of the circle and the point of touch on screen. if the distance in within radius of circle then the touch is inside the drawn circle. I assumme each circle has a different radius. – Raghunandan Mar 14 '13 at 15:44
-
each circle is dynamic and moving, moreover each circle has same radius – Mach Mitch Mar 15 '13 at 08:15
-
use different views for circles to be drawn and you can use views touch listener. I do not know how it will affect performance. For each circle draw use a different view. – Raghunandan Mar 15 '13 at 08:19
-
@MachMitch did u get soln for this ? – ik024 Apr 08 '14 at 07:22
3 Answers
1
When you touch on screen get the x and y co-ordinates. You already know the center of the circle.
//x and y are co-ordiantes when touched.
//center_x and center_y are co-ordinates of the center of the circle.
//R is the radius of the cirlcr
float dx = Math.abs(x-center_x);
float dy = Math.abs(y-center_y);
float R = radius ;//radius of circle.
boolean checkDistance(float dx,float dy,float R)
{
if(dx>R)
{
return false;//outside
}
else if(dy>R)
{
return false;//
}
else
{
return true;
}
}

Thomas Vos
- 12,271
- 5
- 33
- 71

Raghunandan
- 132,755
- 26
- 225
- 256
-
no but my circles r dynamic so it will be horrific to check their location each time – Mach Mitch Mar 15 '13 at 07:51
-
when you draw the circle you can store the center and radius somewhere and use the above to calculate distance. without radius you cannot draw circle. when u dynamically draw store the values and use it in the above code. – Raghunandan Mar 15 '13 at 07:59
0
You can't easily do this with canvas. You should handle touch events by yourself and check which circle you touch based on their coordinates/size/z-index.
But you can make things easier if every circle will be a single view. In such case you'll be able to use standart android touch event listeners. For circles you should create custom view class which will consider circle shape while handling touches.

Leonidos
- 10,482
- 2
- 28
- 37
-
-
You should not draw them by yourself. Use Framelayout and put your views with circles in it. – Leonidos Mar 15 '13 at 08:09
0
why you don't get user drawing coordinate and match them with your circle coordinate..
how to catch user drawing coordinate :
int x = (int) event.getX();
int y = (int) event.getY();

Nasii
- 1
- 2