为什么 toPx() 不能在 Canvas 之外工作?
Why can't toPx() works outside of Canvas?
在下面的代码中,toPx()
在 Canvas
中有效,但在 Surface
中无效。为什么?
Canvas(modifier = Modifier.size(16.dp)) {
val textPaint = Paint().asFrameworkPaint().apply {
textSize = 32.dp.toPx()
}
}
Surface(modifier = Modifier.size(16.dp)) {
val textPaint = Paint().asFrameworkPaint().apply {
textSize = 32.dp.toPx() // Error `toPx()`
}
}
toPx()
函数在提供它的 Density
interface and you cannot use it unless you provide it. The Canvas
works with a DrawScope
中定义。
要使用它,您可以使用 LocalDensity
提供程序提供 Density
。
类似于:
val dpToPx = with(LocalDensity.current) { 32.dp.toPx() }
在下面的代码中,toPx()
在 Canvas
中有效,但在 Surface
中无效。为什么?
Canvas(modifier = Modifier.size(16.dp)) {
val textPaint = Paint().asFrameworkPaint().apply {
textSize = 32.dp.toPx()
}
}
Surface(modifier = Modifier.size(16.dp)) {
val textPaint = Paint().asFrameworkPaint().apply {
textSize = 32.dp.toPx() // Error `toPx()`
}
}
toPx()
函数在提供它的 Density
interface and you cannot use it unless you provide it. The Canvas
works with a DrawScope
中定义。
要使用它,您可以使用 LocalDensity
提供程序提供 Density
。
类似于:
val dpToPx = with(LocalDensity.current) { 32.dp.toPx() }