2

What are widthDp and heightDp as a @Preview parameter?

【My environment】

  • Android Studio Arctic Fox | 2020.3.1 Patch3 build on October 1, 2021
  • Gradle: 7.0.2
  • AGP: 7.0.3
  • androidx.compose.ui:ui-tooling-preview:1.0.1

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?

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121

2 Answers2

3

This is somehow a bug with @Preview, the first composables take the hole space they have, can't explain why. Even without the two parameters widthDp = 200, heightDp = 300, The first Box takes all the space. So for now to get the result you want you have to put a box around which "protects" the main composables.

helpinghand
  • 169
  • 9
2

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.

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121