Tutorials Android How to Convert Pixels to Density Independent (DP) Pixels

How to Convert Pixels to Density Independent (DP) Pixels

The following code snippet shows how to convert device specific pixels to density independent pixels. It returns 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;
}
Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post
Android Tutorials

Convert DP Unit to Equivalent Pixels in Android

Next Post
Android Tutorials

How to Send an Email with Attachment in Android

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
0
Would love your thoughts, please comment.x
()
x