[android] Converting pixels to dp

Kotlin

fun convertDpToPixel(dp: Float, context: Context): Float {
    return dp * (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}

fun convertPixelsToDp(px: Float, context: Context): Float {
    return px / (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}

Java

public static float convertDpToPixel(float dp, Context context) {
    return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

public static float convertPixelsToDp(float px, Context context) {
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to pixel

c++ and opencv get and set pixel color to Mat Calculating width from percent to pixel then minus by pixel in LESS CSS Count all values in a matrix greater than a value Get pixel's RGB using PIL What's the best way to set a single pixel in an HTML5 canvas? Converting pixels to dp Setting width/height as percentage minus pixels How to get screen dimensions as pixels in Android Convert Pixels to Points How to read the RGB value of a given pixel in Python?

Examples related to resolution

Image resolution for new iPhone 6 and 6+, @3x support added? Converting pixels to dp Hide div if screen is smaller than a certain width How can I get screen resolution in java? Set background image according to screen resolution How do I get monitor resolution in Python? Getting the screen resolution using PHP jQuery Screen Resolution Height Adjustment Recommended website resolution (width and height)?

Examples related to dpi

Load dimension value from res/values/dimension.xml from source code Converting pixels to dp How to change resolution (DPI) of an image? getting the screen density programmatically in android?