package com.oliveunion.olive_pro.utils
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.util.DisplayMetrics
import android.util.Log
/*fun Context.pixelsToDp(pixels: Float): Float = pixels * this.resources.displayMetrics.density
fun Context.dpToPixels(dp: Float): Float = dp / this.resources.displayMetrics.density
fun Context.getDensity(): Float = this.resources.displayMetrics.density
fun Context.getScreenWidth(): Int = this.resources.displayMetrics.widthPixels
fun Context.getScreenHeight(): Int = this.resources.displayMetrics.heightPixels
fun getSDKInt(): Int = Build.VERSION.SDK_INT*/
class DisplayUtils {
companion object {
private var mMetrics: DisplayMetrics? = null
private var configuration: Configuration? = null
// val DOUBLE_EPSILON = java.lang.Double.longBitsToDouble(1)
// val FLOAT_EPSILON = java.lang.Float.intBitsToFloat(1)
/**
* initialize method, called inside the Chart.init() method.
*
* @param context
*/
fun init(context: Context?) {
if (context == null) {
Log.e(
"Utils", "Utils.init(...) PROVIDED CONTEXT OBJECT IS NULL"
)
} else {
val res = context.resources
mMetrics = res.displayMetrics
configuration = res.configuration
Log.d("TEST", "dpi : ${mMetrics!!.density}")
}
}
/**
* This method converts dp unit to equivalent pixels, depending on device
* density. NEEDS UTILS TO BE INITIALIZED BEFORE USAGE.
*
* @param dp A value in dp (density independent pixels) unit. Which we need
* to convert into pixels
* @return A float value to represent px equivalent to dp depending on
* device density
*/
fun Float.pixelsToDp(): Float {
if (mMetrics == null) {
Log.e(
"MPChartLib-Utils",
"Utils NOT INITIALIZED. You need to call Utils.init(...) at least once before" +
" calling Utils.convertDpToPixel(...). Otherwise conversion does not " +
"take place."
)
return this
}
return this * mMetrics!!.density
}
/**
* This method converts device specific pixels to density independent
* pixels. NEEDS UTILS TO BE INITIALIZED BEFORE USAGE.
*
* @param px A value in px (pixels) unit. Which we need to convert into db
* @return A float value to represent dp equivalent to px value
*/
fun Float.dpToPixels(): Float {
if (mMetrics == null) {
Log.e(
"MPChartLib-Utils",
("Utils NOT INITIALIZED. You need to call Utils.init(...) at least once before" +
" calling Utils.convertPixelsToDp(...). Otherwise conversion does not" +
" take place.")
)
return this
}
return this / mMetrics!!.density
}
fun getDensity(): Float {
return mMetrics!!.density
}
/*fun getSDKInt(): Int {
return Build.VERSION.SDK_INT
}*/
fun getScreenWidth(): Float {
return mMetrics!!.widthPixels / mMetrics!!.density
}
fun getScreenHeight(): Float {
return mMetrics!!.heightPixels / mMetrics!!.density
}
fun getScreenWidthPixels(): Int {
return mMetrics!!.widthPixels
}
fun getScreenHeightWithPixels(): Int {
return mMetrics!!.heightPixels
}
}
}