Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - pixels to dips

Tags:

android

I have an image of a face (250px X 250px) that is in an absolute layout element. I currently get the user's touch coordinates and using some maths calculate what has been touched (eg the nose), then do something accordingly.

My question is how to scale this to fit the screen width available. If I set the image (in the xml) to fill_parent, the coordinates are way out. Can this be remedied by converting the touch coordinates to dips (if so, how), or will I need to get the screen width (again convert into dips) and sort out the coordinate problem using more maths?

Any and all help appreciated.

like image 542
Rooneyl Avatar asked Apr 08 '11 07:04

Rooneyl


1 Answers

pixels = dps * (density / 160)

The (density / 160) factor is known as the density scale factor, and get be retrieved in Java from the Display Metrics object. What you should do is store the position of the nose etc in terms of dips (which are the same as pixels on a screen with density 160), and then convert dips to pixels depending on what screen you are running on:

final static int NOSE_POSITION_DP = 10;
final float scale = getContext().getResources().getDisplayMetrics().density;
final int nosePositionPixels = (int) (NOSE_POSITION_DP * scale + 0.5f);
like image 130
Joseph Earl Avatar answered Oct 27 '22 00:10

Joseph Earl