Android Pixel to Dip Convert getDpFromPixel(float px, Context context)

Here you can find the source of getDpFromPixel(float px, Context context)

Description

This method converts device specific pixels to density independent pixels.

License

Open Source License

Parameter

Parameter Description
px A value in px (pixels) unit. Which we need to convert into db
context Context to get resources and device specific display metrics

Return

A float value to represent dp equivalent to px value

Declaration

public static float getDpFromPixel(float px, Context context) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;

public class Main {
    /**//from ww  w. j a  v a 2s  .c o m
     * This method converts device specific pixels to density independent pixels.
     *
     * @param px      A value in px (pixels) unit. Which we need to convert into db
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent dp equivalent to px value
     */
    public static float getDpFromPixel(float px, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return px / (metrics.densityDpi / 160f);
    }
}

Related

  1. px2sp(Context context, float pxValue)
  2. px2sp(float pxValue, float fontScale)
  3. pxToDp(Context context, int pxValue)
  4. pxToDp(Context ctx, int px)
  5. pxToSp(Context context, int pxValue)
  6. convertPxtoDp(Context context, int px)
  7. px2dip(Context context, int px)
  8. pixelsAsDp(Context context, int sizeInPx)
  9. pixelsToDpi(Resources res, int pixels)