converts device specific pixels to density independent pixels. - Android android.graphics

Android examples for android.graphics:Pixel

Description

converts device specific pixels to density independent pixels.

Demo Code

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.AnimRes;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

public class Main{

    /**/*from  ww  w  .  ja 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 convertPixelsToDp(float px, Context context) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        float dp = px / (metrics.densityDpi / 160f);
        return dp;
    }

}

Related Tutorials