Saturday, September 26, 2015

android - How to convert pixels to dp

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#dce5ff"
    android:animateLayoutChanges="true"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Convert Pixels to DPs"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="Sans-Serif-Condensed"
        android:textSize="14dp"
        android:layout_below="@id/btn"
        android:textStyle="italic"
        android:textColor="#ff0000"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.content.res.Resources;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;

import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.Context;


public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Create some integer values
                int pixels_first = 37;
                int pixels_second = 22;
                int pixels_third = 43;
                int pixels_fourth = 61;

                /*
                    Context
                        Interface to global information about an application environment.
                        This is an abstract class whose implementation is provided by the
                        Android system. It allows access to application-specific resources and
                        classes, as well as up-calls for application-level operations such as
                        launching activities, broadcasting and receiving intents, etc.
                */
                // Get the Application Context
                Context context = getApplicationContext();

                tv.setText(
                            "Convert Pixels to  integer DPs value\n"+
                            pixels_first+ "pixels = "+ getDPsFromPixels(context, pixels_first) + "dp\n"
                            +pixels_second+ "pixels = "+ getDPsFromPixels(context, pixels_second) + "dp\n"
                            +pixels_third+ "pixels = "+ getDPsFromPixels(context, pixels_third) + "dp\n"
                            +pixels_fourth+ "pixels = "+ getDPsFromPixels(context, pixels_fourth) + "dp\n\n"
                );

                tv.setText(
                            tv.getText()+ "Convert Pixels to  perfect DPs value\n"+
                            pixels_first+ "pixels = "+ getActualDPsFromPixels(context, pixels_first) + "dp\n"
                            +pixels_second+ "pixels = "+ getActualDPsFromPixels(context, pixels_second) + "dp\n"
                            +pixels_third+ "pixels = "+ getActualDPsFromPixels(context, pixels_third) + "dp\n"
                            +pixels_fourth+ "pixels = "+ getActualDPsFromPixels(context,pixels_fourth) + "dp\n"
                );
            }
        });
    }

    // Method for converting pixels value to dps
    public static int getDPsFromPixels(Context context, int pixels){
        /*
            public abstract Resources getResources ()
                Return a Resources instance for your application's package.
        */
        Resources r = context.getResources();
        int  dps = Math.round(pixels/(r.getDisplayMetrics().densityDpi/160f));
        return dps;
    }

    // Method for converting Pixels value to actual DPs (return float value)
    public static float getActualDPsFromPixels(Context context, int pixels){
        /*
            Resources
                Class for accessing an application's resources. This sits on top of the
                asset manager of the application (accessible through getAssets()) and
                provides a high-level API for getting typed data from the assets.

                The Android resource system keeps track of all non-code assets
                associated with an application. You can use this class to access your
                application's resources. You can generally acquire the Resources
                instance associated with your application with getResources().
        */

        /*
            public DisplayMetrics getDisplayMetrics ()
                Return the current display metrics that are in effect for
                this resource object. The returned object should be treated as read-only.

                Returns
                The resource's current display metrics.
        */
        Resources r = context.getResources();
        /*
            public int densityDpi
                The screen density expressed as dots-per-inch. May be
                either DENSITY_LOW, DENSITY_MEDIUM, or DENSITY_HIGH.
        */

        /*
            Density-independent pixel (dp)

                A virtual pixel unit that you should use when defining UI layout,
                to express layout dimensions or position in a density-independent way.

                The density-independent pixel is equivalent to one physical pixel on
                a 160 dpi screen, which is the baseline density assumed by the system
                for a "medium" density screen. At runtime, the system transparently handles
                any scaling of the dp units, as necessary, based on the actual density
                of the screen in use. The conversion of dp units to screen pixels
                is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen,
                1 dp equals 1.5 physical pixels. You should always use dp
                units when defining your application's UI, to ensure proper
                display of your UI on screens with different densities.
        */

        // Math.round() return the nearest whole number
        float  dps = pixels/(r.getDisplayMetrics().densityDpi/160f);
        return dps;
    }
}
More android examples