The issue isn't that toPx() doesn't work at all, but rather that it's being called in the wrong context. 10.dp.toPx() requires a Density context to know the pixel density of the screen. Inside a DrawScope it is accessible implicitly, so you don't need to call it on dp directly.
Here's a breakdown of why your code isn't working as you expect, and how to fix it:
Problem:
10.dp.toPx() is being called outside of the DrawScope (or any Composable that provides a Density context). Without a Density context, toPx() cannot calculate the actual pixel value.
Solution:
Use Density.toPx extension function within the DrawScope. The DrawScope provides access to the current Density implicitly.
Here's the corrected code:
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.example.compose.R // Replace with your actual R file import
fun drawHalfandHalf(scope: DrawScope) {
val midPoint = scope.size.width / 2
val lineWidthPx = 10.dp.toPx(scope.density) // Use Density.toPx()
scope.drawRect(
color = Color.Green,
topLeft = Offset(0f, 0f),
size = scope.size.copy(width = midPoint)
)
scope.drawRect(
color = Color.Red,
topLeft = Offset(midPoint, 0f),
size = scope.size.copy(width = midPoint)
)
scope.drawLine(
color = Color.White,
start = Offset(midPoint, 0f),
end = Offset(midPoint, scope.size.height),
strokeWidth = lineWidthPx
)
}
@Composable
fun Greeting(greetingName: String) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawHalfandHalf(this)
}
Text(
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
color = MaterialTheme.colors.primary,
text = stringResource(R.string.hello_world, greetingName)
)
}
Explanation of changes:
10.dp.toPx(scope.density): Now you are calling toPx by passing the scope's density so the dp can convert to pixels.
Key Takeaway: toPx() needs to be called within a context that provides the screen's density (like a Composable, DrawScope, etc.). If you try to call it outside of such a context, it won't work correctly or throw an exception depending on the Compose version. Always use a qualified Density to call toPx like so: someDp.toPx(density).