Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
GetPositionAndSizeExample()
}
package com.example.test_new_virsion
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.boundsInParent
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun GetPositionAndSizeExample() {
val boxRect = remember { mutableStateOf(Rect.Zero) }
Box(
modifier = Modifier
.size(100.dp)
.background(Color.Blue)
.onGloballyPositioned { coordinates ->
boxRect.value = coordinates.boundsInParent()
},
) {
Text(text = "Left: ${boxRect.value.left} Top: ${boxRect.value.top} Right: ${boxRect.value.right} Bottom: ${boxRect.value.bottom}")
}
// 这里可以使用 boxRect.value 获取到Box组件的位置和大小信息
// boxRect.value.left - 左侧位置
// boxRect.value.top - 顶部位置
// boxRect.value.right - 右侧位置
// boxRect.value.bottom - 底部位置
// boxRect.value.width - 宽度
// boxRect.value.height - 高度
}
@Preview(showBackground = true)
@Composable
fun GetPositionAndSizeExamplePreview() {
MaterialTheme {
GetPositionAndSizeExample()
}
}
文章来源:https://www.toymoban.com/news/detail-715969.html
boxRect.value = coordinates.boundsInParent() 是针对当前父布局。如果想针对整个手机可以用文章来源地址https://www.toymoban.com/news/detail-715969.html
val position = coordinates.positionInWindow()
val top = position.y-StatusBarUtil.getStatusBarHeight(context)
viewModel.boxRect.value = Rect(
left = position.x,
top = top,
right = position.x + coordinates.size.width,
bottom = top + coordinates.size.height
)
LL.e(
TAG,
" \"Left: ${viewModel.boxRect.value.left} Top: ${viewModel.boxRect.value.top} Right: ${viewModel.boxRect.value.right} Bottom: ${viewModel.boxRect.value.bottom}\""
)
//获取状态栏高度
fun getStatusBarHeight(context: Context): Int {
var result: Int = 0
val resourceId: Int = context.getResources().getIdentifier(
"status_bar_height", "dimen", "android"
)
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId)
}
return result
}
到了这里,关于Android Compose 如何获取位置和大小。的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!