新增解析度工具類別

This commit is contained in:
Raymond Yang 2023-08-03 12:09:05 +08:00
parent 8a1ffa8969
commit 6bcf24ddb3
2 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,9 @@
package com.ray650128.floatingwindow
import android.content.res.Resources
val Int.dp: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Int.px: Int
get() = (this / Resources.getSystem().displayMetrics.density).toInt()

View File

@ -0,0 +1,77 @@
package com.ray650128.floatingwindow.utils
import android.content.Context
import android.os.Build
import android.util.DisplayMetrics
import android.view.WindowManager
import com.ray650128.floatingwindow.MyApp
/**
* 畫面尺寸相關工具類別
*/
object DensityUtil {
/**
* 取得螢幕寬度
* @return 螢幕寬度(px)
*/
fun getScreenWidth(): Int {
val windowManager = MyApp.appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val windowMetrics = windowManager.currentWindowMetrics
windowMetrics.bounds.width()
} else {
val metric = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metric)
metric.widthPixels
}
}
/**
* 取得螢幕高度
* @return 螢幕高度(px)
*/
fun getScreenHeight(): Int {
val windowManager = MyApp.appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val windowMetrics = windowManager.currentWindowMetrics
windowMetrics.bounds.height()
} else {
val metric = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metric)
metric.heightPixels
}
}
/**
* 取得狀態列高度
* @return 狀態列高度(px)
*/
fun getStatusBarHeight(): Int {
var result = 0
val resourceId: Int = MyApp.appContext.resources.getIdentifier(
"status_bar_height",
"dimen",
"android"
)
if (resourceId > 0) {
result = MyApp.appContext.resources.getDimensionPixelSize(resourceId)
}
return result
}
/**
* 取得導航列高度
* @return 導航列高度(px)
*/
fun getNavigationBarHeight(): Int {
val resources = MyApp.appContext.resources
val resourceId: Int = resources.getIdentifier("navigation_bar_height", "dimen", "android")
return if (resourceId > 0) {
resources.getDimensionPixelSize(resourceId)
} else 0
}
}