Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - How to rotate an image around the center with canvas

Tags:

flutter

dart

I am trying to implement a custom painter that can draw an image (scaled down version) on the canvas and the drawn image can be rotated and scaled.

I get to know that to scale the image I have to scale the canvas using scale method.

Now the questions is how to rotate the scaled image on its center (or any other point). The rotate method of canvas allow only to rotate on top left corner.

Here is my implementation that can be extended

like image 749
Natwar Singh Avatar asked Jul 13 '18 10:07

Natwar Singh


People also ask

How do I rotate an image in canvas flutter?

It can be used like this: 1Transform( 2 angle: bacteria. rotation, 3 transform: Matrix4. rotationZ( 4 0.25 5 ), 6 child: Container( 7 width: 24, 8 height: 24, 9 color: Colors.

How do you rotate something in canvas?

The rotate() method allows you to rotate a drawing object on the canvas. The rotate() method accepts a rotation angle in radians. If the angle is positive, the rotation is clockwise. In case the angle is negative, the rotation is counterclockwise.

How do you rotate a picture 90 degrees in flutter?

Rotate Widget with RotatedBox(): Rotate box can only be used to rotate 90o, 180o and 270o.


1 Answers

Had the same problem, Solution was simply making your own rotation method in three lines

void rotate(Canvas canvas, double cx, double cy, double angle) {
  canvas.translate(cx, cy);
  canvas.rotate(angle);
  canvas.translate(-cx, -cy);
}

We thus first move the canvas towards the point you want to pivot around. We then rotate along the the topleft (default for Flutter) which in coordinate space is the pivot you want and then put the canvas back to the desired position, with the rotation applied. Method is very efficient, requiring only 4 additions for the translation and the rotation cost is identical to the original one.

like image 155
Wouter Vandenputte Avatar answered Nov 14 '22 07:11

Wouter Vandenputte