You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:50:34