Skip to content

Instantly share code, notes, and snippets.

@Hayk985
Created March 3, 2022 12:14
Show Gist options
  • Save Hayk985/ba0945ef7d8da2289f07119dfa77504e to your computer and use it in GitHub Desktop.
Save Hayk985/ba0945ef7d8da2289f07119dfa77504e to your computer and use it in GitHub Desktop.
import android.content.Context
import android.graphics.Point
import android.os.Build
import android.view.WindowManager
import kotlin.math.pow
import kotlin.math.sqrt
/**
* An extension function to return current device real width and height
*/
fun WindowManager.currentDeviceRealSize(): Pair<Int, Int> {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
return Pair(
maximumWindowMetrics.bounds.width(),
maximumWindowMetrics.bounds.height())
} else {
val size = Point()
defaultDisplay.getRealSize(size)
Pair(size.x, size.y)
}
}
/**
* Utility class, where I've collected all the functions from my medium
* article - https://medium.com/@hayk.mkrtchyan8998/cracking-android-screen-sizes-88228822-98b28d23260c
*
* @param context - to get DisplayMetrics instance
* @param windowManager - to use the above extension function.
*
* You can retrieve windowManager instance from the activity.
*/
class SizeUtils(
private val context: Context,
private val windowManager: WindowManager
) {
/**
* Doesn't return correct values most of the time
*/
private val displayMetrics = context.resources.displayMetrics
private val density = displayMetrics.density //The scale factor of the density
private val densityDpi = displayMetrics.densityDpi // The density of the screen
/**
* Works more accurate
*/
private val xdpi = displayMetrics.xdpi // The pixels count in inch for screen width
private val ydpi = displayMetrics.ydpi // The pixels count in inch for screen height
/**
* The below function returns current device
* screen width and height in inches
*/
fun getScreenWidthAndHeightInInches(): Pair<Float, Float> {
val (width, height) = windowManager.currentDeviceRealSize()
val displayMetrics = context.resources.displayMetrics
val widthInInches = width / displayMetrics.xdpi
val heightInInches = height / displayMetrics.ydpi
return Pair(widthInInches, heightInInches)
}
/**
* Calculate screen size using Pythagorean theorem
*/
fun getDeviceScreenSize(): Double {
val (width, height) = windowManager.currentDeviceRealSize()
val widthInInches: Double = (width / xdpi).toDouble()
val heightInInches: Double = (height / ydpi).toDouble()
val widthAndHeightSum = widthInInches.pow(2) + heightInInches.pow(2)
val screenSize = sqrt(widthAndHeightSum)
/* Or instead of above 2 lines of code we can write
val screenSize = hypot(widthInInches, heightInInches)
*/
return screenSize
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment