Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert pixels into dip(Density Independent Pixels) in Android

Tags:

android

In my Android application I have pixels(69px) and I need to convert this pixels into dip(Density Independent Pixels).

Any suggestions?

like image 941
user1195614 Avatar asked Apr 10 '12 18:04

user1195614


People also ask

How do you convert pixels to dp?

Pixel values can be converted to DP by dividing the pixel value by the screen pixel density.

Is dp same as px?

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 difference between dp and SP in Android?

SP: is an abbreviation for Scale independent pixels. It is the same as the dp unit, but it is additionally scaled according to the user's font size selection. DP: A virtual pixel unit used to communicate layout dimensions or location in a density-independent manner while creating UI layout.


2 Answers

Just divide your value in pixels by DisplayMetrics.density.

like image 80
Romain Guy Avatar answered Oct 13 '22 00:10

Romain Guy


Hope this will be helpful

Resources r = getResources();
float dp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 69, r.getDisplayMetrics());
like image 30
Basbous Avatar answered Oct 12 '22 22:10

Basbous