如何在Kotlin中导入DpRect.toRect()扩展函数?
正确导入方式及调用注意事项
toRect()是Density作用域下的DpRect扩展函数,正确的导入语句为:
import androidx.compose.ui.unit.toRect
你之前尝试的该导入语句看似正确,但无效大概率是调用场景的问题:
- 这个函数必须在具备
Density上下文的环境中调用,比如@Composable函数内部(Compose可组合函数默认自带Density上下文)。 - 若在非
@Composable环境调用,需要手动传入Density实例,通过作用域函数包裹调用逻辑。
可组合函数内调用示例
import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.ui.unit.DpRect import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.toRect @Composable fun ExampleCard() { val cardWidth = 180f.dp val cardHeight = 270f.dp val fullHeight = 296f.dp val focusRect = DpRect(0f.dp, 0f.dp, cardWidth, fullHeight).toRect() // 后续使用focusRect... Box {} }
非可组合函数内调用示例
import androidx.compose.ui.unit.DpRect import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.toRect import androidx.compose.ui.unit.Density fun nonComposableHandler(density: Density) { val cardWidth = 180f.dp val cardHeight = 270f.dp val fullHeight = 296f.dp val focusRect = density.run { DpRect(0f.dp, 0f.dp, cardWidth, fullHeight).toRect() } }
内容的提问来源于stack exchange,提问作者Mars
相关产品推荐
相关产品推荐

