Well, i been trying to figure out, is there a simple way to pass from dp or milimetres or even inches to px. (like: 6dp would be 20px) It seems everything is usually done in px but i want to use these in orther to keep the proportions in different screens and have a rough sense of how big is going to be (guessing with pixels feels really...bothering) Thanks in advance and sorry if the question is too vague.
Asked
Active
Viewed 113 times
0
-
This might be the answer you are looking for http://stackoverflow.com/questions/4605527/converting-pixels-to-dp – Longi Jan 22 '15 at 00:46
-
Im not sure it is. what kind of class is TypedValue? – qera hile Jan 22 '15 at 00:49
-
@qerahile it's a class that allows you to convert from one unit to another http://developer.android.com/reference/android/util/TypedValue.html – samgak Jan 22 '15 at 01:59
1 Answers
1
There is no way to convert milimetres or even inches to px programmatically. If you want to support different screens, you can follow the document here. To convert dp to px, you can also use the following method:
/**
* Convert dp to px.
* @param context
* @param dp the input dp.
* @return the output px.
*/
public static int dpToPx(Context context, int dp) {
float density = context.getResources().getDisplayMetrics().density;
return (int) (dp * density + 0.5);
}
Update:
Here is how to get a device's width and height pixels:
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;

Lei Guo
- 2,550
- 1
- 17
- 22
-
This is what i was looking for! One more thing, so you cant know the width and height of a device(in metrics or pixels)? – qera hile Jan 22 '15 at 14:26
-
Yes, you can know the width and height of a device in pixels, see my update. But, in order to support many screens, you must consider use dp instead of px. – Lei Guo Jan 22 '15 at 14:39