首先,我们需要使用androidx.core:core-ktx:1.6.0
依赖库中的Insets
属性来测量状态栏、导航栏等系统装饰视图的高度。
val systemPadding = rememberInsets {
it.systemBars
}
然后,我们可以在页面中使用Box
组件包裹需要显示在状态栏下方的图片,并设置Box
的padding
属性为systemPadding.top
的值,以便将图片下移。
Box(
contentAlignment = Alignment.TopCenter,
modifier = Modifier.fillMaxSize().padding(top = systemPadding.top)
) {
Image(
painter = painterResource(id = R.drawable.image),
contentDescription = null,
modifier = Modifier.fillMaxWidth().height(200.dp),
contentScale = ContentScale.Crop
)
}
最后,我们需要在主题文件中设置状态栏为透明色。这可以通过在themes.xml
中将
改为
来完成。
完整示例代码:
@Composable
fun ImageUnderStatusBar() {
val systemPadding = rememberInsets {
it.systemBars
}
Box(
contentAlignment = Alignment.TopCenter,
modifier = Modifier.fillMaxSize().padding(top = systemPadding.top)
) {
Image(
painter = painterResource(id = R.drawable.image),
contentDescription = null,
modifier = Modifier.fillMaxWidth().height(200.dp),
contentScale = ContentScale.Crop
)
}
}
@Composable
fun MyApp() {
MaterialTheme {
ImageUnderStatusBar()
}
}
// themes.xml