Android Kotlin: How to convert Pixels to DP

Converting Pixels to DP in Android with Kotlin

This code snippet demonstrates how to convert pixel values to density-independent pixels (dp) in an Android application written with Kotlin. Dp is a unit that adjusts to different screen densities, ensuring consistent layout across devices.

The code consists of two main parts: the MainActivity class and extension functions.

Functionality Breakdown:

  1. MainActivity.kt:

    • The onCreate method generates a random pixel value (pixels).
    • It then calls two extension functions, pixelsToDp and pixelsToDpInt, to convert the pixel value to dp.
    • Finally, the results (dp and dpInt) are displayed on the TextView.
  2. Extension Functions:

    • pixelsToDp(context: Context): Float: This function takes an integer pixel value and a context object. It calculates the dp equivalent by dividing the pixel value by the device's density ratio and returns the result as a float.
    • pixelsToDpInt(context: Context): Int: Similar to the previous function, it calculates the dp value but returns the result as an integer by rounding the float value.

Summary:

By utilizing these extension functions, developers can easily convert pixel values to dp for consistent and device-independent UI layouts in their Android applications written with Kotlin. This approach ensures optimal representation across various screen densities.


MainActivity.kt

package com.example.jetpack

import android.content.Context
import android.os.Bundle
import android.util.DisplayMetrics
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.random.Random


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // generate a random integer number in range
        val pixels = Random.nextInt(50,200)

        // convert pixels to equivalent dp value
        val dp = pixels.pixelsToDp(this)
        val dpInt = pixels.pixelsToDpInt(this)

        // show pixels to dp actual float value
        textView.text = "Return float value"
        textView.append("\n$pixels pixels = $dp dp")

        // pixels to dp integer conversion result
        textView.append("\n\nReturn integer value")
        textView.append("\n$pixels pixels = $dpInt dp")
    }
}


// extension function to convert pixels to dp
// this method return dp perfect float value
fun Int.pixelsToDp(context: Context):Float{
    return this / (context.resources
        .displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT).toFloat()
}


// extension function to convert pixels value to dp value
// this method return integer dp value
fun Int.pixelsToDpInt(context: Context):Int{
    return this / (context.resources
        .displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#E5E4E2">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="16dp"
        tools:text="TextView"
        android:fontFamily="sans-serif-condensed"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials