Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Convert Px to Dp (Video Aspect Ratio) [duplicate]

Possible Duplicate:
converting pixels to dp in android

I'm trying to convert pixels to dp. What is the formula?

Lets convert 640 and 480 into dp. The docs say this

The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160)

But I don't think that is what I need (and I don't know how to use this). I guess I just need the forumla. I have the code ready:

DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    switch(metrics.densityDpi)
    {
         case DisplayMetrics.DENSITY_LOW:
         int sixForty = ?
         int fourEighty = ?
         break;

         case DisplayMetrics.DENSITY_MEDIUM:
         int sixForty = ?
         int fourEighty = ?
         break;

         case DisplayMetrics.DENSITY_HIGH:
         int sixForty = ?
         int fourEighty = ?
         break;
    }
like image 824
spentak Avatar asked Jul 11 '11 21:07

spentak


People also ask

Is dp the same as PX?

The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

How many pixels is a dp?

One dp is a virtual pixel unit that's roughly equal to one pixel on a medium-density screen (160dpi; the "baseline" density). Android translates this value to the appropriate number of real pixels for each other density.

What is the difference between PX dip dp and SP?

px - one pixel Corresponds to actual pixels on the screen. Pixel is the smallest controllable element of a picture represented on the screen. sp - Scale-independent Pixels This is like the dp unit. scaled by the user's font size preference.


1 Answers

Instead of trying to infer the dp conversion factor from the screen's density classification, you can simply query it directly:

getWindowManager().getDefaultDisplay().getMetrics(metrics); float logicalDensity = metrics.density; 

logicalDensity will then contain the factor you need to multiply dp by to get physical pixel dimensions for the device screen.

int px = (int) Math.ceil(dp * logicalDensity); 
like image 126
mportuesisf Avatar answered Oct 05 '22 02:10

mportuesisf