Created
February 2, 2023 11:36
-
-
Save EmmanuelGuther/0672a48a8dc3af15b0681f7ad5023417 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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