Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have created my application with the height and width given in pixel for a pantech device whose resolution is 480x800.

I need to convert the the height and width for an G1 device. I thought converting it into dp will solve the prob and provide same solution for both the device.

is there any easy way to convert the pixels to dp?? or any suggestions??

share|improve this question

10 Answers

/// Converts 14 dip into its equivalent px

Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, r.getDisplayMetrics());
share|improve this answer
23  
Note: The above is converting DIPs to Pixels. The original question asked how to convert pixels to Dips! – Amorgos Mar 13 '12 at 16:34
1  
Here's a real answer to the OP: stackoverflow.com/questions/6656540/… – Linus Apr 7 '12 at 1:34
12  
Its funny how the answer is more helpful when it doesn't really answer the question -_- I thought I wanted what the question asked then I realized I didn't! So great answer. I do have a question. How can I obtain the last paramter for applyDimension? Can I just do getResource().getDisplayMetrics(), or is there something else? – Andy Aug 4 '12 at 3:30
/**
 * This method converts dp unit to equivalent pixels, depending on device density. 
 * 
 * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent px equivalent to dp depending on device density
 */
public static float convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return px;
}

/**
 * This method converts device specific pixels to density independent pixels.
 * 
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent dp equivalent to px value
 */
public static float convertPixelsToDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return dp;
}
share|improve this answer
1  
stackoverflow.com/a/5960030/480850 worked better for me px->dp. – Richard Apr 27 at 1:07
Use ´Resources.getSystem().getDisplayMetrics()´ if you don't have a Context handy. – TomTasche Jun 5 at 10:02

According to the Android Development Guide:

px = dp * (dpi / 160)

But often you'll want do perform this the other way around when you receive a design that's stated in pixels. So:

dp = px / (dpi / 160)

If you're on a 240dpi device this ratio is 1.5 (like stated before), so this means that a 60px icon equals 40dp in the application.

share|improve this answer
1  
private float dpFromPx(float px)
{
    return px / this.getContext().getResources().getDisplayMetrics().density;
}


private float pxFromDp(float dp)
{
    return dp * this.getContext().getResources().getDisplayMetrics().density;
}
share|improve this answer
float density = context.getResources().getDisplayMetrics().density;
float px = someDpValue * density;
float dp = somePxValue / density;

'density' equals 1.0 on mdpi, 1.5 on hdpi and 0.75 on ldpi.

share|improve this answer

You should use dp just as you would pixels. That's all they are; display independent pixels. Use the same numbers you would on a medium density screen, and the size will be magically correct on a high density screen.

However, it sounds like what you need is the fill_parent option in your layout design. Use fill_parent when you want your view or control to expand to all the remaining size in the parent container.

share|improve this answer
actually my problem is my application is coded for high density screen and now it needs to be converted to low density screen.. – Indhu Jan 6 '11 at 4:44
modify your pixels for a medium density screen (you can set up a medium density screen in the emulator) and replace the pixel with dp. However, more flexible applications can be made using fill_parent and multiple layouts. – Michael Lowman Jan 6 '11 at 12:20
Finally, i had no option but to change all the px to dp manually.. :( – Indhu Jan 12 '11 at 13:18
1  
At least next time you'll use dp first and won't have to change anything :) Although it should be possible to use layouts that don't require absolute positioning for most things. – Michael Lowman Jan 12 '11 at 13:22
Since it was my first app.. i made this mistake... i ll never do it again...:) – Indhu Jan 12 '11 at 13:59

PX and DP are different but similar.

DP is the resolution when you only factor the physical size of the screen. When you use DP it will scale your layout to other similar sized screens with different pixel densities.

Occasionally you actually want pixels though, and when you deal with dimensions in code you are always dealing with real pixels, unless you convert them.

So on a android device, normal sized hdpi screen, 800x480 is 533x320 in DP (I believe). To convert DP into pixels /1.5, to convert back *1.5. This is only for the one screen size and dpi, it would change depending on design. Our artists give me pixels though and I convert to DP with the above 1.5 equation.

share|improve this answer

You can therefore use the following formulator to calculate the right amount of pixels for a dimension specified in dp

   public int convertToDp(int input) {
            // Get the screen's density scale
            final float scale = getResources().getDisplayMetrics().density;
            // Convert the dps to pixels, based on density scale
            return (int) (input * scale + 0.5f);
    }
share|improve this answer
1  
This converts dp to pixels but you called your method convertToDp. – Qwertie Jul 3 '12 at 22:33

I use that optimized class:

public final class DimensionUtils {

    private static boolean isInitialised = false;
    private static float pixelsPerOneDp;

    private static void initialise(View view) {
        pixelsPerOneDp = view.getResources().getDisplayMetrics().densityDpi / 160f;
        isInitialised = true;
    }

    public static float pxToDp(View view, float px)
    {
        if (!isInitialised) {
            initialise(view);
        }

        return px / pixelsPerOneDp;
    }

    public static float dpToPx(View view, float dp)
    {
        if (!isInitialised) {
            initialise(view);
        }

        return dp * pixelsPerOneDp;
    }
}
share|improve this answer

It is my personal experience by working in Phonegap technology for both platform (iOS and Android) you can set pixels for your media query or other JS, jQuery functionality for iOS device because its ratio is fixed. But you cant set this pixel ratio for Android untill you will not focus on particular device and checking in device because Android devices has pixels ratio like 1.3, 1.5 and it is depends on it. you cant fix one for all in Phonegap. I have intex its resolution is 480x800 for developing i need to develope in 320x508px and it is different for other company devices. I think you will understand

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.