I have an image in ImageView. I need to know the exact (x,y) coordinate of the image when I touch the image. I also want to draw a circle on the touch place.
Given below, is the code I use. I have an ImageView and I attach a onTouchListener to it.
The problem is this:
- I get weird (x,y) values
-
new circles are only drawn 3 times. After that no new circles are drawn!
ImageView touch=(ImageView) findViewById(R.id.image); touch.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN){ //Paint p = new Paint(Paint.ANTI_ALIAS_FLAG); //Canvas can=new Canvas(bm); p.setColor(Color.RED); float fx=event.getX(); float fy=event.getY(); can.drawCircle(fx, fy, 20, p); } return true; } });
The problem is most likely that you aren’t taking into account the fact that the position of the
MotionEventis adjusted to be relative to the containing view (theImageViewin this case) and it looks like you are attempting to draw them on anotherCanvaswhich would have a different coordinate space. If you need the two to be separate like this, I would recommend usingMotionEvent.getRawX()andMotionEvent.getRawY()so that the touch values are in the coordinates of the screen as a whole.However, if you just want to draw the circles over the image, a better solution would be to subclass
ImageViewso you can detect touches in itsonTouchEvent()method directly (instead of a listener) and do custom drawing in itsonDraw()method, guaranteeing everything is in the same adjusted coordinate plane.It is not apparent from your code why this operation would only work correctly three times. Perhaps try only returning
truefrom the touch detection method in the DOWN instance that you are interested in. You may be unnecessarily stealing touch events with the current implementation.HTH