AndroidAndroid UIAndroid Utility

Android Convert DP, SP, Pixel Programmatically

In this tutorial i will show you how to convert a value from DP to pixel, SP to Pixel and vica versa. These are the methods used by all the Android developers every day.

You may find may tutorials about the same topic but here i am trying to give better explanation and presented as easy to use kotlin methods.

Let’s have a look into each one by one.

DP to Pixel Conversion

Where method’s first argument is dp (density-independent pixels), which is the dp value of our dimension. Second argument is the application context.

fun dpToPx(dp: Float, context: Context): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()).toInt()
}

SP to Pixel Conversion

Where method’s first argument is sp (scalable pixels), which is the sp value of the dimension. Second argument is the application context.

fun spToPx(sp: Float, context: Context): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.resources.displayMetrics).toInt()
}

Pixel To DP Conversion

Where method’s first argument is pixel, which is the actual pixel value of the dimension. Second argument is the application context.

fun pxToDp(px: Float, context: Context?): Int {
    return (px.toInt() / resources.displayMetrics.density).toInt()
}

Pixel To SP Conversion

Where method’s first argument is pixel, which is the actual pixel value of the dimension. Second argument is the application context.

fun pxToSp(px: Float, context: Context?): Int {
    return (px.toInt() / resources.displayMetrics.scaledDensity).toInt()
}

Usage – Example

Let’s see how we can use these methods in our activity.

class MainActivity2 : AppCompatActivity() {

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

        val imgDemo = findViewById<ImageView>(R.id.imgDemo)
        imgDemo.layoutParams.width = dpToPx(100f, applicationContext)
        imgDemo.layoutParams.height = pxToDp(300f, applicationContext)
    }
}
About author

Rojer is a programmer by profession, but he likes to research new things and is also interested in writing. Devdeeds is his blog, where he writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

Your email address will not be published. Required fields are marked *