Gabriel
Gabriel

Reputation: 49

Do I need to parse Int to dp before using the .dp extension function in compose?

Suppose I have a screen in figma with 1080x1920 resolution, then I add 20px padding, when I recreate this layout with compose I need to parse 20 to dp (using some utility function like: val Int.dp: Int get() = (this * Resources.getSystem().displayMetrics.density + 0.5f).toInt()) or can I just use 20.dp?

Currently I only use .dp extension and I never had a problem.

Upvotes: 1

Views: 1243

Answers (1)

stoyan_vuchev
stoyan_vuchev

Reputation: 601

You don't have to parse anything manually. If you need to set a padding, width or height to a composable via Modifier, then using the Dp implementation is the way to go. But if you need to paint something on a Canvas or do some low-level layout measurements e.g. using constraints to define an Offset, then converting a dp to px value is the way to go. Such conversion can be done by using the toPx(), toDp(), and many more Density methods. Keep in mind that these methods are accessible only within a Density context.

Here is a basic application of a padding using dp:

Text(
    modifier = Modifier.padding(horizontal = 16.dp),
    text = "This text has a horizontal padding of 16."
)

An example of drawing a square on a Canvas using dp to px conversion:

Canvas(
    modifier = Modifier
        .width(200.dp)
        .height(100.dp),
    onDraw = {

        // Convert dp to px.
        val squareSize = 50.dp.toPx()

        drawRect(
            color = Color.Blue,
            size = Size(
                width = squareSize,
                height = squareSize
            )
        )

    }
)

And if you need to convert values when Density context is not provided:

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

SubcomposeLayout { constraints ->

    /// ...

    layout(
        width = constraints.maxWidth,
        height = constraints.maxHeight
    ) {

        /// ...

        val itemOffsetX = previousItemOffsetX + spacing

    }

    /// ...

}

Upvotes: 2

Related Questions