Set touch listeners on canvas drawings

2019-05-21 03:44发布

问题:

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.

回答1:

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.



回答2:

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;
 }
 }


回答3:

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();