Android Compose 中如何正确获取控件位置、尺寸、PivotX/PivotY等属性
Compose 中获取组件属性(尺寸、位置、变换基点)的实现方案
1. 获取组件尺寸
你目前使用的onSizeChanged是官方推荐的标准实现,不属于不优雅的方案,只需要把尺寸值存在可观察状态中,即可在代码其他位置访问:
// 声明状态存储组件尺寸,默认值为0 var componentSize by remember { mutableStateOf(IntSize.Zero) } Image( modifier = Modifier .rotate(rotation) .onSizeChanged { // 组件尺寸变化时自动更新状态 componentSize = it }, painter = painterResource(id = R.drawable.ic_champers), contentDescription = "Image" ) // 代码任意位置访问尺寸 val width = componentSize.width.toFloat() val height = componentSize.height.toFloat()
2. 获取组件位置
使用onGloballyPositioned修饰符可以拿到组件的各类坐标信息,对应原View体系的x、y属性:
// 存储坐标状态 var positionInParent by remember { mutableStateOf(Offset.Zero) } var positionInScreen by remember { mutableStateOf(Offset.Zero) } Image( modifier = Modifier .rotate(rotation) .onSizeChanged { componentSize = it } .onGloballyPositioned { coordinates -> // 相对于父容器的坐标,对应原View的x、y positionInParent = coordinates.positionInParent() // 相对于整个屏幕的坐标 positionInScreen = coordinates.positionInRoot() }, painter = painterResource(id = R.drawable.ic_champers), contentDescription = "Image" ) // 访问坐标 val x = positionInParent.x val y = positionInParent.y
3. 获取/设置 PivotX/PivotY(变换基点)
Compose 中rotate、scale等变换修饰符默认的变换基点是组件中心,对应原View默认的pivotX = width/2、pivotY = height/2。
自定义基点
直接在变换修饰符中传入pivot参数即可自定义基点:
// 示例:设置旋转基点为组件左上角 Image( modifier = Modifier.rotate(rotation, pivot = Offset(0f, 0f)), // 其余参数省略 )
访问当前基点
基点参数由开发者主动传入修饰符,只需要把基点存在可观察状态中即可全局访问:
var pivot by remember { mutableStateOf(Offset.Zero) } var componentSize by remember { mutableStateOf(IntSize.Zero) } Image( modifier = Modifier .rotate(rotation, pivot = pivot) .onSizeChanged { componentSize = it // 尺寸变化时自动更新默认中心基点 pivot = Offset(it.width / 2f, it.height / 2f) }, // 其余参数省略 ) // 访问基点 val pivotX = pivot.x val pivotY = pivot.y
内容的提问来源于stack exchange,提问作者Xavier Armengol
相关产品推荐
相关产品推荐

