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 - 左側(cè)位置
// boxRect.value.top - 頂部位置
// boxRect.value.right - 右側(cè)位置
// boxRect.value.bottom - 底部位置
// boxRect.value.width - 寬度
// boxRect.value.height - 高度
}
@Preview(showBackground = true)
@Composable
fun GetPositionAndSizeExamplePreview() {
MaterialTheme {
GetPositionAndSizeExample()
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-715969.html
? boxRect.value = coordinates.boundsInParent() 是針對當(dāng)前父布局。如果想針對整個手機(jī)可以用文章來源地址http://www.zghlxwxcb.cn/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}\""
)
//獲取狀態(tài)欄高度
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
}
到了這里,關(guān)于Android Compose 如何獲取位置和大小。的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!