val x = nextOffset.x + lineLength * kotlin.math.sin(angle)
val y = nextOffset.y + lineLength * kotlin.math.cos(angle)
rather than rotating the canvas, you can use
sin
and
cos
to calculate the target
x
and
y
Here’s a full example
Copy code
Canvas(
modifier = Modifier.fillMaxSize()
) {
var nextOffset = Offset(0f, 0f)
repeat(noOfLines) {
val angle = (0..360).random().toFloat()
val x = nextOffset.x + lineLength * kotlin.math.sin(angle)
val y = nextOffset.y + lineLength * kotlin.math.cos(angle)
val targetOffset = Offset(x, y)
drawLine(
color = colors.random(),
strokeWidth = 5f,
start = nextOffset,
end = targetOffset
)
nextOffset = targetOffset
}
}
m
Michael Paus
11/01/2021, 8:57 AM
Instead of fiddling around with sines and cosines yourself, you could also create a rotation matrix and apply that to the draw scope for drawing. In addition you can apply it to any coordinate to see where it will be in the rotated system. This is more efficient and less error prone.