Is there any way to measure a Composable before dr...
# compose
t
Is there any way to measure a Composable before drawing without getting the siize aferward with .onSizeChanged?
v
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
the problem is there is no actuall width and height they are only the constraints of the composable
t
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
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.