开发者文档提供了如何convert dp units to pixel units 的答案:
在某些情况下,您需要以 dp 表示尺寸,然后
将它们转换为像素。 dp 单位到屏幕像素的转换是
简单:
px = dp * (dpi / 160)
提供了两个代码示例,一个 Java 示例和一个 Kotlin 示例。这是 Java 示例:
// 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...
Kotlin 示例:
// 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...
}
我从 Java 示例创建的 Java 方法运行良好:
/**
* 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;
}
此问题的其他几个答案提供了与此答案类似的代码,但其他答案中没有足够的支持文档让我知道其他答案之一是否正确。接受的答案也与此答案不同。我认为developer documentation 使 Java 解决方案变得清晰。
Compose 中也有一个解决方案。 Compose 中的 Density 为与设备无关的像素 (dp) 和像素之间的转换提供了一行 solution。
val sizeInPx = with(LocalDensity.current) { 16.dp.toPx() }