Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Dp to Px in Kotlin - This cast can never succeed

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?

like image 436
S. Czop Avatar asked Jan 28 '19 07:01

S. Czop


1 Answers

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 :)

like image 168
pentexnyx Avatar answered Nov 05 '22 18:11

pentexnyx