Question

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:

  1. I get weird (x,y) values
  2. 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;
        }
    });
    
Was it helpful?

Solution

The problem is most likely that you aren't taking into account the fact that the position of the MotionEvent is adjusted to be relative to the containing view (the ImageView in this case) and it looks like you are attempting to draw them on another Canvas which would have a different coordinate space. If you need the two to be separate like this, I would recommend using MotionEvent.getRawX() and MotionEvent.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 ImageView so you can detect touches in its onTouchEvent() method directly (instead of a listener) and do custom drawing in its onDraw() 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 true from 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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top