Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] How to rotate a canvas path without rotate the canvas in Jetpack Compose

Posted on November 11, 2022 By

Solution 1 :

Canvas has rotate function that can rotate and DrawScope function it’s wrapped with.

Canvas(modifier =Modifier.fillMaxSize()){
    rotate(degrees = angle){
        // Anything you draw is rotated by this angle
    }
    // Things you draw here are not rotated
}

Problem :

I want to create a Canvas APP on Compose Desktop to draw molecule structure, when clicking on window, the canvas will draw a straigth a line, I am using Path() class in Compose, but I want to rotate the Path() when clicking on window. I am using cos() and sin() function to calculate the endpoint of current straight line, but I want a better way to draw a rotated line on canvas.

By the way, since I am using Compose Multiplatform framework, so Jetpack Compse solution should work fine for me.

My current code is as follow:

package customCanvas

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.graphics.Path
import kotlin.math.cos
import kotlin.math.sin


@Composable
fun customCanvas(){
    var currentPosition by remember { mutableStateOf(Offset.Unspecified) }
    var previousPosition by remember { mutableStateOf(Offset.Unspecified) }
    var currentPath by remember { mutableStateOf(Path()) }
    val paths = remember { mutableStateListOf<Path>() }
    val randomAngle = listOf<Float>(45f, -45f)

    Canvas(
        modifier = Modifier
            .fillMaxSize()
            .background(color = Color.Gray)
            .pointerInput(Unit) {
                forEachGesture {
                    awaitPointerEventScope {
                        awaitFirstDown().also {
                            currentPosition = it.position
                            println("position: ${it.position}")
                            previousPosition = currentPosition
                            currentPath.moveTo(currentPosition.x, currentPosition.y)   //change the current path position to clicked coordinate on canvas
                            val angle = randomAngle.random()

                            // ***get the end point of the path useing cos() and sin()***
                            val toPoint = getPointByAngle(40f, angle, Pair(currentPosition.x, currentPosition.y))
                            currentPath.lineTo(toPoint.first, toPoint.second)

                            paths.add(currentPath) //add the "path" to a paths Array so coroutine can draw the line on canvas latter

                        }
                    }
                }
            }
    ){
        with(drawContext.canvas.nativeCanvas) {
            val checkPoint = saveLayer(null, null)
            paths.forEach { it: Path ->
                drawPath(
                    color = Color.Black,
                    path = it,
                    style = Stroke(
                        width = 4f,
                        cap = StrokeCap.Round,
                        join = StrokeJoin.Round,
                    )
                )
            }
        }
    }
}

//calculate the end point x and y coordinate by cos() and sin()
fun getPointByAngle(length: Float, angle: Float, startPoint: Pair<Float, Float>): Pair<Float, Float> {
    return Pair(startPoint.first + length * cos(angle), startPoint.second + length * sin(angle))
}

Comments

Comment posted by HYPERLUCKEMIA

Thanks! But I wanted to get the end point coordinates of the line, is there any to get that after canvas rotated?

READ  [FIXED] android - making a smooth looking app launcher icon
Powered by Inline Related Posts

Android Tags:android-jetpack-compose, canvas, kotlin-coroutines, kotlin-multiplatform

Post navigation

Previous Post: What is the 21 day fitness challenge?
Next Post: [FIXED] android – Waiting for coroutine finish before fragment close

Related Posts

[FIXED] android – How can i retrieve currently logged in users data like contact,email,name,etc Android
[FIXED] android – Google play keeps asking me to remove REQUEST_INSTALL_PACKAGES, but my merged manifest does not have it Android
[FIXED] java – frida calls the wrong constructor Android
[FIXED] android – I have some problem about step Counter Google fit API Android
[FIXED] android – Kotlin – “Inappropriate Block Method Call” when making Bluetooth Connection inside Coroutine Android
[FIXED] How can I banned an iOS & Android devices from login to my app Android

Archives

  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • Can Vicks humidifier be used without filter?
  • What color is Spanish green?
  • How old is Jamie in The War That Saved My Life?
  • When should I use scalp massager for hair growth?
  • Can I put polyurethane over liming wax?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme