c_phil
c_phil

Reputation: 283

Draw lines at an angle in jetpack compose without a canvas

so I wanted to draw a line at an angle from point A to point B in jetpack compose.
Is there a way to do it without a canvas, since a canvas won't really work with what I want to do

Upvotes: 3

Views: 2824

Answers (1)

Ma3x
Ma3x

Reputation: 6549

If you want to draw behind other composables you can use the drawBehind modifier.

If you want to draw both behind and in front you can use the drawWithContentmodifier.

If you also want to cache the result as much as possible you can use the drawWithCache modifier.

Example of a line behind the content and a line in front of the content using the drawWithCache modifier

@Composable
fun DrawWithCacheExample() {
    val width = 400.dp
    val height = 200.dp
    var offsetX by remember { mutableStateOf(0f) }
    Box(
        modifier = Modifier
            .size(width, height)
            .border(1f.dp, Color.Black, RectangleShape)
            .drawWithCache {
                onDrawWithContent {
                    // draw behind the content
                    drawLine(Color.Black, Offset.Zero, Offset(width.toPx(), height.toPx()), 1f)
                    // draw the content
                    drawContent()
                    // draw in front of the content
                    drawLine(Color.Black, Offset(0f, height.toPx()), Offset(width.toPx(), 0f), 1f)
                }
            }
    ) {
        Box(modifier = Modifier
            .size(width / 2, height / 2)
            .offset { IntOffset(offsetX.roundToInt(), (height / 4).roundToPx()) }
            .background(Color.Yellow)
            .draggable(
                orientation = Orientation.Horizontal,
                state = rememberDraggableState { delta ->
                    offsetX += delta
                }
            )
        )
    }
}

Upvotes: 4

Related Questions