Skip to content

Instantly share code, notes, and snippets.

@am3n
Created July 11, 2019 08:46
Show Gist options
  • Save am3n/d2c89c8f678ab83f2491a4940bb70357 to your computer and use it in GitHub Desktop.
Save am3n/d2c89c8f678ab83f2491a4940bb70357 to your computer and use it in GitHub Desktop.
Convert (Float/Int) and (Dp/Px) to each other with Kotlin Extensions :) in android
package com.example
import android.content.res.Resources
val Int.iPx2Dp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt()
val Int.iDp2Px: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Int.fPx2Dp: Float get() = this / Resources.getSystem().displayMetrics.density
val Int.fDp2Px: Float get() = this * Resources.getSystem().displayMetrics.density
val Float.iPx2Dp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt()
val Float.iDp2Px: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Float.fPx2Dp: Float get() = this / Resources.getSystem().displayMetrics.density
val Float.fDp2Px: Float get() = this * Resources.getSystem().displayMetrics.density
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment