'How can I set the Paint style when I use drawLine in Android Jetpack Compose?

I'm learning Jetpack Compose Canvas. I know that drawIntoCanvas() — Provides access to draw directly with the underlying Canvas. This is helpful for situations to re-use alternative drawing logic in combination with DrawScope.

I want to use different style line for different goal, such as:

Style 1:  color = Color.Blue , strokeWidth = 3f,...   
Style 2:  color = Color.Red ,  strokeWidth = 4f, ...   

I can re_use thses styles with Code B. I hope to I can re_use these style with Code A, how can I do?

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,
            strokeWidth = 3f      
        )
    }

}

Code B

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


    val linePaint2 = Paint()
    linePaint2.isAntiAlias = true
    linePaint2.style = PaintingStyle.Stroke
    linePaint2.color = Color.Red


    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),
               linePaint1
            )

            it.drawLine(
               Offset(x = 10f, y = canvasHeight-50),
               Offset(x = canvasWidth-10, y = 10f),
               linePaint2
            )

        }

    }

}


Solution 1:[1]

There is no reason not to use drawInCanvas, and the DrawScope you are calling in A is meant to be stateless and does not depens on androids Paint class. If you must use paint objects, you could create an extension like so:

fun DrawScope.drawLine(
    start: Offset?,
    end: Offset?,
    paint: Paint,
    blendMode: BlendMode? = DefaultBlendMode
) = drawLine(
    start,
    end,
    paint.strokeWidth,
    paint.strokeCap.toStrokeCap(),
    paint.pathEffect.toComposePathEffect(),
    paint.alpha.toFloat() / 255f,
    paint.colorFilter.asComposeColorFilter(),
    blendMode
)

fun Paint.Cap.toStrokeCap() = when(this) {
    Paint.Cap.BUTT -> StrokeCap.Butt
    Paint.Cap.SQUARE -> StrokeCap.Square
    Paint.Cap.ROUND -> StrokeCap.Round
}

Since there is only a difference in color, I encourage you not to use this method and just call the existing drawLine function. If you must use paints, use this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 770grappenmaker