Set touch listeners on canvas drawings

谁说胖子不能爱 提交于 2019-12-10 10:47:12

问题


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


来源:https://stackoverflow.com/questions/15413370/set-touch-listeners-on-canvas-drawings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!