Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Matrix4 to rotate a Container by its center?

Tags:

math

flutter

I have an AnimatedContainer, and I want to rotate it by 180 degrees, and the origin should be at its center.

It has a transform parameter that, unfortunately, asks for a Matrix4.

There is no explanation of Matrix4 in the Flutter documentation: https://api.flutter.dev/flutter/vector_math_64/Matrix4-class.html

What is the Matrix4 I must use to rotate it by its center?

like image 977
MarcG Avatar asked Aug 21 '19 17:08

MarcG


3 Answers

I've found the answer and just made this package (to do all kinds of transformations, not only rotate by the center): https://pub.dev/packages/matrix4_transform

var height = 30;
var width = 30;

AnimatedContainer(
   color: Colors.red, 
   width: width, 
   height: height,
   transform:
     Matrix4Transform()
       .rotateDegrees(180, origin: Offset(width/2, height/2))
       .matrix4,
);
like image 71
MarcG Avatar answered Nov 10 '22 12:11

MarcG


There is no need to use a Matrix4 for a simple 180 degrees rotation. Use RotationTransition to wrap your AnimatedContainer instead. RotationTransition takes a turns parameter, which is an Animation<T> whose value can be used to represent the RotationTransition's child widget rotation in radians. This way, you can control your rotation animation via an AnimationController. Check out this example from the Flutter official GitHub to find out more.

like image 5
drogel Avatar answered Nov 10 '22 11:11

drogel


You can specify the alignment using the transformAlignment field.

AnimatedContainer(
  duration: Duration(seconds: 1),
  transform: Matrix4.rotationZ(_yourAngle),
  transformAlignment: Alignment.center,
  child: YourWidget(),
)
like image 1
tudorprodan Avatar answered Nov 10 '22 11:11

tudorprodan