What are differents between drawLine directly and drawLine wrapped in drawIntoCanvas in Jetpack Compose?

Viewed 116

I'm learning Jetpack Compose Canvas.

I met the two different Code both Code A and Code B.

Code A invoke drawLine directly, and Code B invoke drawLine which is wrapped in drawIntoCanvas.

1: What are differents between Code A and Code B ?

2: Which one is the better between Code A and Code B ?

Code A

@Composable
fun setCanvas() {
    Canvas(
        modifier = Modifier
            .fillMaxSize()
    ) {
        val canvasWidth = size.width
        val canvasHeight = size.height

        drawLine(
            start = Offset(x = 0f, y = canvasHeight),
            end = Offset(x = canvasWidth, y = 0f),
            color = Color.Blue      
        )
    }

}

Code B

@Composable
fun setCanvas() {
    val linePaint = Paint()
    linePaint.isAntiAlias = true
    linePaint.style = PaintingStyle.Stroke
    linePaint.color = Color.Blue

    Canvas(
        modifier = Modifier
            .fillMaxSize()
    ) {
        val canvasWidth = size.width
        val canvasHeight = size.height

        drawIntoCanvas {
            it.drawLine(
               Offset(x = 0f, y = canvasHeight),
               Offset(x = canvasWidth, y = 0f),
               linePaint
            )
        }

    }

}
1 Answers

Function drawIntoCanvas has access to the underlying Canvas with nativeCanvas (quite helpful if you can to reuse some draw logic you implemented in previous Android apps). Then, you can call all the methods related to the native Canvas like drawText() or drawVertices() for example.

Related