Android Dip to Pixel Convert getPixelFromDp(float dp, Context context)

Here you can find the source of getPixelFromDp(float dp, Context context)

Description

This method converts dp unit to equivalent pixels, depending on device density.

License

Open Source License

Parameter

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

Return

A float value to represent px equivalent to dp depending on device density

Declaration

public static float getPixelFromDp(float dp, 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 {
    /**/*  ww  w  . ja v  a2s  .com*/
     * This method converts dp unit to equivalent pixels, depending on device density.
     *
     * @param dp      A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public static float getPixelFromDp(float dp, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return dp * (metrics.densityDpi / 160f);
    }
}

Related

  1. formatDipToPx(Context context, float dip)
  2. sp2px(Context context, float spValue)
  3. sp2px(Context context, float spValue)
  4. spToPx(Context context, int spValue)
  5. convertToPixel(Context context, float dp)
  6. convertDptoPx(Context context, int dp)
  7. dip2px(Context context, int dip)
  8. dipValue(Context context, int dip)
  9. dip2pixel(Context context, float n)