如何将 xml 中的 android:radius 转换为 Kotlin Android 中的浮点值

How to convert android:radius in xml to float value in Kotlin Android

我有一个可绘制的背景 xml 文件如下,我将视图的半径设置为 40dp:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid
        android:color="@color/jungleGreen"/>
    <corners
        android:bottomLeftRadius="40dp"
        android:topLeftRadius="40dp"/>
</shape>

出于一些特定原因,我需要在 Kotlin 中以编程方式执行相同的操作 Android。所以我写了一个函数如下:

private fun setupGraphBackground(view: View) {
        val gradientDrawable = GradientDrawable()
        gradientDrawable.shape = GradientDrawable.RECTANGLE
        gradientDrawable.setColor(resources.getColor(R.color.jungleGreen))
        gradientDrawable.setStroke(0, null)
        gradientDrawable.cornerRadii = floatArrayOf(45f, 45f, 0f, 0f, 0f, 0f, 45f, 45f)
        view.background = gradientDrawable
    }

基本上,我发现如果我在我的函数中将值设置为 45f,它可能与 xml 文件中的 40dp 接近。

我的问题是,是否有任何规则可以将其转换为完全正确的数字?似乎到处都没有文档。

如有任何帮助,我们将不胜感激。

谢谢。

您以编程方式设置的任何值都被视为一个像素。您实际上应该将您想要的 dp 值转换为像素。你可以用这个方法

fun dpToPx(context: Context, dp: Float): Float {
    return dp * (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}

然后像这样使用它

private fun setupGraphBackground(view: View) {
    val gradientDrawable = GradientDrawable()
    val rad = dpToPx(context, 40f)
    gradientDrawable.shape = GradientDrawable.RECTANGLE
    gradientDrawable.setColor(resources.getColor(R.color.jungleGreen))
    gradientDrawable.setStroke(0, null)
    gradientDrawable.cornerRadii = floatArrayOf(rad, rad, 0f, 0f, 0f, 0f, rad, rad)
    view.background = gradientDrawable
}

您还可以创建一个 UIUtils class 并将此方法添加到伴随对象中,以便您可以从任何需要的地方调用它。