Android Compose 设置宽高比
在 Compose 中,可以使用 Modifier.aspectRatio 来设置可组合项的宽高比。
aspectRatio 修饰符接受一个浮点数作为参数,表示宽高比。 例如,aspectRatio(1f) 表示宽度和高度相等,aspectRatio(16f / 9f) 表示宽高比为 16:9。
以下是一些示例
//正方形
Image(
painter = painterResource(id = R.drawable.my_image),
contentDescription = "My Image",
modifier = Modifier.aspectRatio(1f)
)
// 16:9 的图像
Image(
painter = painterResource(id = R.drawable.my_image),
contentDescription = "My Image",
modifier = Modifier.aspectRatio(16f / 9f)
)
aspectRatio 修饰符还可以接受一个可选的 matchHeightConstraintsFirst 参数。 如果此参数设置为 true,则可组合项将首先尝试匹配高度约束,然后根据宽高比调整宽度。 如果设置为 false(默认值),则可组合项将首先尝试匹配宽度约束, 然后根据宽高比调整高度
// 首先匹配高度约束
Image(
painter = painterResource(id = R.drawable.my_image),
contentDescription = "My Image",
modifier = Modifier.aspectRatio(16f / 9f, matchHeightConstraintsFirst = true)
)
请注意,aspectRatio 修饰符会根据可组合项的父级布局和自身的约束来确定最终的尺寸。 因此,可能需要结合其他修饰符(例如 fillMaxWidth 或 size)来实现所需的布局效果。