Skip to content

Instantly share code, notes, and snippets.

@EmmanuelGuther
Created February 2, 2023 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmmanuelGuther/0672a48a8dc3af15b0681f7ad5023417 to your computer and use it in GitHub Desktop.
Save EmmanuelGuther/0672a48a8dc3af15b0681f7ad5023417 to your computer and use it in GitHub Desktop.
private val displayMetrics: DisplayMetrics by lazy { Resources.getSystem().displayMetrics }
/**
* Returns boundary of the screen in pixels (px).
*/
val screenRectPx: Rect
get() = displayMetrics.run { Rect(0, 0, widthPixels, heightPixels) }
/**
* Returns boundary of the screen in density independent pixels (dp).
*/
val screenRectDp: RectF
get() = screenRectPx.run { RectF(0f, 0f, right.px2dp, bottom.px2dp) }
/**
* Returns boundary of the physical screen including system decor elements (if any) like navigation
* bar in pixels (px).
*/
val Context.physicalScreenRectPx: Rect
get() =
(applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager)
.run { DisplayMetrics().also { defaultDisplay.getRealMetrics(it) } }
.run { Rect(0, 0, widthPixels, heightPixels) }
/**
* Returns boundary of the physical screen including system decor elements (if any) like navigation
* bar in density independent pixels (dp).
*/
val Context.physicalScreenRectDp: RectF
get() = physicalScreenRectPx.run { RectF(0f, 0f, right.px2dp, bottom.px2dp) }
/**
* Converts any given number from pixels (px) into density independent pixels (dp).
*/
val Number.px2dp: Float
get() = this.toFloat() / displayMetrics.density
/**
* Converts any given number from density independent pixels (dp) into pixels (px).
*/
val Number.dp2px: Int
get() = (this.toFloat() * displayMetrics.density).roundToInt()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment