Home > Software engineering >  How to convert dp to float in kotlin?
How to convert dp to float in kotlin?

Time:11-12

I want to get middle of the users screen while in activity and I tried to convert DisplayMetrics to Float. The error says "Unresolved reference." How do I get Float from DisplayPixels? Heres my code:

val dpFloat = dp.toFloat()

I wanted to get Float from DisplayMetrics.

CodePudding user response:

If I understand correctly, your question.

What you need is the following:

val scale = resources.displayMetrics.density
val dpToFloat = (sizeInDp * scale)

To put it more clearly, you can simplify this into this Kotlin extension function:

fun Float.dpToFloat(): Float {
    val scale = resources.displayMetrics.density
    return (this * scale)
}

CodePudding user response:

I have these extension functions and use them a lot. I wish it helps you.

import android.content.res.Resources
import kotlin.math.ceil

val Int.dpf: Float
    get() {
        return dp.toFloat()
    }


val Float.dpf: Float
    get() {
        return dp.toFloat()
    }

val Int.dp: Int
    get() {
        return if (this == 0) {
            0
        } else ceil((Resources.getSystem().displayMetrics.density * this).toDouble()).toInt()
    }

val Float.dp: Int
    get() {
        return if (this == 0f) {
            0
        } else ceil((Resources.getSystem().displayMetrics.density * this).toDouble()).toInt()
    }

Usage examples:

10.dp       // Int   -> Int
10.dpf      // Int   -> Float
(10.5f).dp  // Float -> Int
(10.5f).dpf // Float -> Float
  • Related