androidandroid-jetpack-composeandroid-jetpack-compose-preview

Jetpack Compose - About Preview widthDp and heightDp


What are widthDp and heightDp as a @Preview parameter?

【My environment】

Here is my code.

@Preview(
    showBackground = true,
    widthDp = 200,
    heightDp = 200,
)
@Composable
fun DefaultPreview() {
    Box(modifier = Modifier.size(100.dp).background(Color.Red))
}

And preview shows below.
enter image description here

But I expected below.
enter image description here

It seems that the box size is larger than I expected. Does anyone explain that?


Solution

  • From Preview.kt codebase,

    @param widthDp Max width in DP the annotated @[Composable] will be rendered in. Use this to restrict the size of the rendering viewport.
    @param heightDp Max height in DP the annotated @[Composable] will be rendered in. Use this to restrict the size of the rendering viewport.

    The parameters are to restrict the maximum rendering viewport.
    It seems they scale the composable if the given dimensions are large/smaller than the actual dimensions of the composable.