Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Dp to pixels in Android Jetpack Compose?

Most of Jetpack Compose API uses Dp as a dimensions unit, but sometimes a pixel value is required. How can I convert a dp value to px? Just for an example there's graphicsLayer() modifier that accepts translationX/Y arguments in pixels.

like image 433
Valeriy Katkov Avatar asked Jan 27 '21 15:01

Valeriy Katkov


People also ask

What is DP in jetpack compose?

Public companion properties. A dimension used to represent a hairline drawing element.

How many pixels is a DP?

One dp is a virtual pixel unit that's roughly equal to one pixel on a medium-density screen (160dpi; the "baseline" density). Android translates this value to the appropriate number of real pixels for each other density.


Video Answer


1 Answers

There're toPx() and roundToPx() methods defined by Density interface, you can use it like this:

import androidx.compose.ui.platform.LocalDensity

val pxValue = with(LocalDensity.current) { 16.dp.toPx() }

// or

val pxValue = LocalDensity.current.run { 16.dp.toPx() }

Such an expression might look confusing if you're new to Kotlin language so let's break it down and see how it works. toPx() is an extension function of Dp class, you can think of it as a Dp class method. But since toPx() is defined inside Density interface, you cannot use it unless you provide a density as a receiver. And at last you can get the current density from an CompositionLocal named LocalDensity.

like image 171
Valeriy Katkov Avatar answered Oct 02 '22 20:10

Valeriy Katkov