Home > Mobile >  Jetpack Compose - Draw Line with Pattern
Jetpack Compose - Draw Line with Pattern

Time:11-18

I'm looking to draw a line on a canvas with a pattern instead of a color. Here's the code I have right now:

drawLine(
    color = progressColor,
    start = Offset(if (whiteGap) progressCapWidth else startOffsetBg, yOffset),
    end = Offset(endOffsetProgress, yOffset),
    strokeWidth = progressHeight.toPx(),
    cap = if (roundedCorners) StrokeCap.Round else StrokeCap.Butt,
)

It's part of a custom linear progress bar. Per the design I was given, they want the progress to have this pattern:

enter image description here

This is an example of full progress with this diagonally patterned progress. Is it possible to use a drawable and repeat it instead of a color? Is there a way to just apply/create diagonal white gaps directly in when drawing the line?

We're implementing this whole feature using Jetpack Compose, so I can't do something with traditional XML involved.

CodePudding user response:

Here's how you can draw it with Canvas:

Canvas(
    Modifier
        .padding(top = 100.dp)
        .border(1.dp,Color.Black)
        .padding(10.dp)
        .height(30.dp)
        .fillMaxWidth()
        .clip(CircleShape)
) {
    val step = 10.dp
    val angleDegrees = 45f
    val stepPx = step.toPx()
    val stepsCount = (size.width / stepPx).roundToInt()
    val actualStep = size.width / stepsCount
    val dotSize = Size(width = actualStep / 2, height = size.height * 2)
    for (i in -1..stepsCount) {
        val rect = Rect(
            offset = Offset(x = i * actualStep, y = (size.height - dotSize.height) / 2),
            size = dotSize,
        )
        rotate(angleDegrees, pivot = rect.center) {
            drawRect(
                Color.Blue,
                topLeft = rect.topLeft,
                size = rect.size,
            )
        }
    }
}

Result:

  • Related