Question: On Android Studio Java, I need to find the percentage coordinates when I click anywhere on an imageView. This imageView is placed near the middle

On Android Studio Java, I need to find the percentage coordinates when I click anywhere on an imageView. This imageView is placed near the middle of the screen in a Constraint Layout. When I click on any location in that imageView, I need to get the percentage coordinates because I am then using those percentage coordinates to programmatically place a textView at that location by setting the constraints of this textView with these percentage coordinates.

I have a setOnTouchListener for this imageView where I do:

x = (int) event.getX();

y = (int) event.getY();

However, these x and y coordinates will be pixel coordinates. I need to convert them to percentage coordinates.

To do this conversion:

x [percent] = 100 * (x [in pixel] / Resolution Width)

y [percent] = 100 * (y [in pixel] / Resolution Height)

I know that you can find the Resolution height and width of the whole screen by doing:

DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int height = displayMetrics.heightPixels; int width = displayMetrics.widthPixels;

However, I am trying to find the coordinates within the imageView and hence, the resolution height/width will be different (smaller) as compared to the entire screen.

In Java in Android Studio, how can I find the percent coordinates when I click at any location within the ImageView?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!