converts dp unit to equivalent device specific value in pixels - Android android.graphics

Android examples for android.graphics:Pixel

Description

converts dp unit to equivalent device specific value in pixels

Demo Code

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

public class Main {

  /**//ww w.j  ava 2s .com
   * This method converts dp unit to equivalent device specific value in pixels.
   * 
   * @param dp
   *          A value in dp(Device 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 Pixels equivalent to dp according to
   *         device
   */
  public static float convertDpToPixel(float dp, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return px;
  }

}

Related Tutorials