Converts dp unit to equivalent pixels, depending on device density. - Android Graphics

Android examples for Graphics:Pixel

Description

Converts dp unit to equivalent pixels, depending on device density.

Demo Code


//package com.java2s;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.util.TypedValue;

public class Main {
    /**//w  w  w  . j a  v a2s .  c o m
     * Converts dp unit to equivalent pixels, depending on device density.
     *
     * @param context Context to get resources and device specific display metrics
     * @param dp      A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public static float convertDpToPixel(@NonNull Context context, float dp) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                metrics);
    }
}

Related Tutorials