Riny
Riny

Reputation: 159

Android calculate length or distance between two points in Canvas

enter image description here I have an image drawn using canvas. And I mark two points and a line between them on the canvas. I need to calculate the length of the line or the distance between the two points. I use the formula Math.sqrt((x2-x1)(x2-x1)+(y2-y1)(y2-y1)) to calculate distance between two points and get a value like 250.82 or so. The resultant values is in pixels. How can I convert them to metric values or in the units of mm and cm ? I find many pixel to cm calculators online but they give me wrong answer which doesnt match with the real distance between two points. Can someone help me pls ?

Upvotes: 2

Views: 2557

Answers (1)

Josef Raška
Josef Raška

Reputation: 1301

You can use this:

public static float getRealCm(int pixels, DisplayMetrics displayMetrics)
    {
        float dpi = (float) displayMetrics.densityDpi;

        float inches = pixels / dpi;

        return inches * 2.54f; //inches to cm
    }

DisplayMetrics can be obtained from Resources. You can write in your activity: getResources().getDisplayMetrics()

Upvotes: 2

Related Questions