• Latest Code...

    Featured Post

    Implementing Hilt in a Kotlin Android Jetpack Compose Project with MVVM Architecture

     In modern Android development, maintaining a scalable codebase can be challenging, especially when it comes to dependency management. Hilt,...

    Convert Dp to Px and Px to Dp in Android or Android Studio

    In Android documentation ,

    dp( Density-independent Pixels) - An abstract unit that is based on the physical density of the screen.These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen's dpi.

    px(Pixels) - Corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.

    Here, we discussed about how to convert px to dp and dp to px,

    public static int convertPixelToDp(int pixel, Context mContext) {
    float pixels = pixel;
    // Get the screen's density scale
    final float scale = mContext.getResources().getDisplayMetrics().density;
    // Convert the dps to pixels, based on density scale
    return (int) (pixels * scale + 0.5f);
        }

        public static int convertPixelsToDp(int px, Context context) {
    Resources resources = context.getResources();
    float dp = px * context.getResources().getDisplayMetrics().density;
    return (Math.round(dp));
        }
    or
        public static int pxToDp(int px) {
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
        }


    More you can learn about pixel and dp from https://www.google.com/design/spec/layout/units-measurements.html#units-measurements-density-independent-pixels-dp-
    and
    directly convent and see the values: http://labs.rampinteractive.co.uk/android_dp_px_calculator/

    Happy Coding !!!

    Contact Form

    Name

    Email *

    Message *