https://kotlinlang.org logo
#compose
Title
# compose
t

TheMrCodes

02/22/2021, 7:08 PM
Is there any way to measure a Composable before drawing without getting the siize aferward with .onSizeChanged?
v

Vitor Prado

02/22/2021, 7:14 PM
you can use
BoxWithConstraints
inside this composable you have access to :
Copy code
/**
     * The constraints given by the parent layout in pixels.
     *
     * Use [minWidth], [maxWidth], [minHeight] or [maxHeight] if you need value in [Dp].
     */
    val constraints: Constraints
    /**
     * The minimum width in [Dp].
     *
     * @see constraints for the values in pixels.
     */
    val minWidth: Dp
    /**
     * The maximum width in [Dp].
     *
     * @see constraints for the values in pixels.
     */
    val maxWidth: Dp
    /**
     * The minimum height in [Dp].
     *
     * @see constraints for the values in pixels.
     */
    val minHeight: Dp
    /**
     * The minimum height in [Dp].
     *
     * @see constraints for the values in pixels.
     */
    val maxHeight: Dp
t

TheMrCodes

02/22/2021, 8:25 PM
the problem is there is no actuall width and height they are only the constraints of the composable
t

Tash

02/22/2021, 10:01 PM
Depending on what you want to do with the resulting
width
/
height
you can intercept with
Modifier.layout
Copy code
Modifier.layout { measurable, constraints ->
    val placeable = measurable.measure(constraints)
    val width = placeable.width
    val height = placeable.height
    ...
}
n

Nader Jawad

02/23/2021, 12:04 AM
Do you have an example of the use case? We introduced
Modifier.drawWithCache
to give an opportunity to allocate graphics objects when sizing information is known and re-use those objects within the corresponding
onDraw
block wihin the implementation. This is useful to create gradients with sizing information known upfront or Paths and re-use he result across draw calls as long as the size has not changed or state parameters being read do not change.
2 Views