Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting pixels to dp

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

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

Is there any easy way to convert pixels to dp?
Any suggestions?

like image 293
Indhu Avatar asked Jan 05 '11 15:01

Indhu


People also ask

How many pixels is a dp?

Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen.

Is dp same as pixels?

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.

How many pixels is 4 inches 300 DPI?

For example, a 4 inches wide object scanned at 300 DPI will have 1200 pixels on a computer screen.

Is dp and DPI the same?

In Android, we have a baseline density of 160 dots-per-inch(dpi). So, for a 160 dpi screen, we have 1 pixel = 1 dp and 320 dpi screen, we have 2 pixels = 1 dp which is 2x. Let's say we have a tablet of 1280*800 pixels, 160 dpi and phone of 800*1280 pixels, 320 dpi. Their pixel resolution is the same.


1 Answers

Java code:

// Converts 14 dip into its equivalent px float dip = 14f; Resources r = getResources(); float px = TypedValue.applyDimension(     TypedValue.COMPLEX_UNIT_DIP,     dip,     r.getDisplayMetrics() ); 

Kotlin code:

 val dip = 14f  val r: Resources = resources  val px = TypedValue.applyDimension(      TypedValue.COMPLEX_UNIT_DIP,      dip,      r.displayMetrics  ) 

Kotlin extension:

val Number.toPx get() = TypedValue.applyDimension(   TypedValue.COMPLEX_UNIT_DIP,   this.toFloat(),   Resources.getSystem().displayMetrics) 
like image 145
prasobh Avatar answered Sep 19 '22 13:09

prasobh