Tutorials Android Convert DP Unit to Equivalent Pixels in Android

Convert DP Unit to Equivalent Pixels in Android

The following code snippet shows how to converts DP unit to equivalent pixels, depending on device density. It returns 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;
}
Total
0
Shares
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Benjamin Noffsinger
Benjamin Noffsinger
5 years ago

Where does the magic number 160 come from? [Edit] Nevermind, I should read more before I open my mouth. DP = 1.0 on a 160 dpi screen.

Previous Post

How to Generate Gravtar Image Url from Email in Java

Next Post
Android Tutorials

How to Convert Pixels to Density Independent (DP) Pixels

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
1
0
Would love your thoughts, please comment.x
()
x