16

I ran into a problem while coding in Kotlin. I copy-pasted a java code sample that converts DP to Pixels, in order to place it as a parameter for setting padding programatically. I was expecting the IDE to automatically transform it all to Kotlin, however it failed in the process.

The code in Java looks like the following:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

After the translation to Kotlin:

val scale = resources.displayMetrics.density
val dpAsPixels = (sizeInDp * scale + 0.5f) as Int 

The cast as Int is marked with the error

"This cast can never succeed"

How can this be fixed?

Zoe
  • 27,060
  • 21
  • 118
  • 148
S. Czop
  • 602
  • 1
  • 6
  • 17

5 Answers5

33

Why not trying it with an Extension Function such as

val Int.dp: Int get() = (this / getSystem().displayMetrics.density).toInt()

to convert to DP and

val Int.px: Int get() = (this * getSystem().displayMetrics.density).toInt()

to convert to Pixels?

Hope it helps :)

nyx69
  • 747
  • 10
  • 21
7

The error can be solved by removing the cast as Int and instead replace it with the method .toInt()

val scale = resources.displayMetrics.density
val dpAsPixels = (16.0f * scale + 0.5f).toInt()
S. Czop
  • 602
  • 1
  • 6
  • 17
6

If you have value in dimens.xml

<dimen name="textSize">24dp</dimen>

Then, you can get value in pixel as Int

val value = resources.getDimensionPixelSize(R.dimen.textSize)
  • This one seems a good approach since we can separate dimens depends on screen resolution aswell. – Arul Feb 15 '23 at 11:09
2

Extensions.kt file

val Int.dp: Int
    get() = (toFloat() * Resources.getSystem().displayMetrics.density + 0.5f).toInt()
reznic
  • 672
  • 6
  • 9
0

You can try these extension functions, it doesn't need context and for Int values it rounds it up to next integer value.

private fun getDip(): Float = Resources.getSystem().displayMetrics.density
fun Float.dp() = this * getDip()
fun Int.dp() = (this * getDip()).roundToInt()

and you can use it like this:

val width = 48.dp()
val height = 2.5f.dp()
Homayoon Ahmadi
  • 1,181
  • 1
  • 12
  • 24