Barrufet
Barrufet

Reputation: 683

Get information about size before is drawn in Compose

So I want to get the compose height/width before it's drawn into UI screen, does anyone know if it's possible to do that? And if yes, how?

I tried Modifier.onPlaced { } but I think it's already drawn into the UI before I do any modification with that information

Upvotes: 3

Views: 3039

Answers (1)

Thracian
Thracian

Reputation: 66516

If you provide code i might be able to provide more specific sample of SubcomposeLayout but i use it to measure dimensions of a Composable without triggering recomposition and when BoxWithConstraints is not enough. As in link in comment under some conditions maxWidth or height does not match composable dimensions.

I use it subcompose some section of Composables to pass required dimensions or like building a Slider with dynamic thumb size, chat rows, and so on. I posted several answer about SubcomposeLayout. You can check out this link to see some samples

The recent one i use is a sample one with single main and dependent Composables as in this link

@Composable
internal fun DimensionSubcomposeLayout(
    modifier: Modifier = Modifier,
    mainContent: @Composable () -> Unit,
    dependentContent: @Composable (DpSize) -> Unit
) {

    val density = LocalDensity.current
    SubcomposeLayout(
        modifier = modifier
    ) { constraints: Constraints ->

        // Subcompose(compose only a section) main content and get Placeable
        val mainPlaceable: Placeable = subcompose(SlotsEnum.Main, mainContent)
            .map {
                it.measure(constraints.copy(minWidth = 0, minHeight = 0))
            }.first()


        val dependentPlaceable: Placeable =
            subcompose(SlotsEnum.Dependent) {
                dependentContent(
                    DpSize(
                        density.run { mainPlaceable.width.toDp() },
                        density.run { mainPlaceable.height.toDp() }
                    )
                )
            }
                .map { measurable: Measurable ->
                    measurable.measure(constraints)
                }.first()


        layout(mainPlaceable.width, mainPlaceable.height) {
            dependentPlaceable.placeRelative(0, 0)
        }
    }
}

/**
 * Enum class for SubcomposeLayouts with main and dependent Composables
 */
enum class SlotsEnum { Main, Dependent }

Passing a Composable as mainContent param will return its size in Dp without recomposition for dependentContent.

Upvotes: 2

Related Questions