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?
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.
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.
For example, a 4 inches wide object scanned at 300 DPI will have 1200 pixels on a computer screen.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With