Search code examples
androidandroid-imageviewandroid-scrollview

How to calculate touched position of ImageView in ScrollView, Considering Zoom factor?


I have an image that should be click-able in certain areas, say 26 areas in that Image. What's the best way to do that ?

enter image description here

I made an image with same size, each click-able area in Image has specific color, with white background, so when the image is clicked, I can get the Pixel color of second image in that position and realize which area is clicked.

The problem is, i need to show picture in ScrollView, and image is resized to fit the screen width. I know i can calculate the clicked offset using event.getRawY() + sv.getScrollY();, but how to calculate the zoom factor ?

Actually since both images are the same size, i need to calculate the clicked position considering zoom factor to find the precise position of that pixel in second Image.


Solution

  • i think this snipped help you.

       @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.imageView1 || v.getId() == R.id.image_scrollview) {
    
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) event.getX();
                startY = (int) event.getY();
                break;
            case MotionEvent.ACTION_UP:
                int cordinate_Y = (int) ((event.getY() + v.getScrollY()) / diffH);
                int cordinate_X = (int) ((event.getX() + v.getScrollX()) / diffW);
                if ((Math.abs((int) event.getX() - startX) > 10)
                        || (Math.abs((int) event.getY() - startY) > 10)) {
                    break;
                }
    
                int pixelColor = bitmap.getPixel(cordinate_X, cordinate_Y);
                if (pixelColor != -1) {
                    showDetails(texts[map.get(pixelColor)],
                            images[map.get(pixelColor)],
                            titles[map.get(pixelColor)]);
    
                }
    
                break;
    
            }
        }
    
        return false;
    }