I am drawing a line in `Canvas` and then `rotatin...
# compose
v
I am drawing a line in
Canvas
and then
rotating
it by
angle 45f
, is there a way to get that
end Offset
till the line is rotated How can I get/access this Offset
(?,?)
?
a
Seems like "Point in circle" https://math.stackexchange.com/a/260115 You have angle (45f), and radius (100)
🙏 1
t
Copy code
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
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.
1
🙏 1
v
Thanks gonna try