The developer docs provide an answer on how to convert dp units to pixel units:
In some cases, you will need to express dimensions in dp and then
convert them to pixels. The conversion of dp units to screen pixels is
simple:
px = dp * (dpi / 160)
Two code examples are provided, a Java example and a Kotlin example. Here is the Java example:
// The gesture threshold expressed in dp
private static final float GESTURE_THRESHOLD_DP = 16.0f;
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
mGestureThreshold = (int) (GESTURE_THRESHOLD_DP * scale + 0.5f);
// Use mGestureThreshold as a distance in pixels...
The Kotlin example:
// The gesture threshold expressed in dp
private const val GESTURE_THRESHOLD_DP = 16.0f
...
private var mGestureThreshold: Int = 0
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Get the screen's density scale
val scale: Float = resources.displayMetrics.density
// Convert the dps to pixels, based on density scale
mGestureThreshold = (GESTURE_THRESHOLD_DP * scale + 0.5f).toInt()
// Use mGestureThreshold as a distance in pixels...
}
The Java method that I created from the Java example works well:
/**
* Convert dp units to pixel units
* https://developer.android.com/training/multiscreen/screendensities#dips-pels
*
* @param dip input size in density independent pixels
* https://developer.android.com/training/multiscreen/screendensities#TaskUseDP
*
* @return pixels
*/
private int dpToPixels(final float dip) {
// Get the screen's density scale
final float scale = this.getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
final int pix = Math.round(dip * scale + 0.5f);
if (BuildConfig.DEBUG) {
Log.i(DrawingView.TAG, MessageFormat.format(
"Converted: {0} dip to {1} pixels",
dip, pix));
}
return pix;
}
Several of the other answers to this question provide code that is similar to this answer, but there was not enough supporting documentation in the other answers for me to know if one of the other answers was correct. The accepted answer is also different than this answer. I thought the developer documentation made the Java solution clear.
There is also a solution in Compose. Density in Compose provides a one line solution for the conversions between device-independent pixels (dp) and pixels.
val sizeInPx = with(LocalDensity.current) { 16.dp.toPx() }
px
,dp
,sp
conversion formulas – Redound