Reputation: 128
In Flutter, I can rotate a Widget using the Transform Widget. However, the rotation is around origin specified in the Transform widget properties rather than around the current focal point.
I tried modifying the Matrix by translating to the focal point, rotating, and then translating back.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: new TransformContainer(),
),
);
}
}
class TransformContainer extends StatefulWidget {
const TransformContainer({
Key key,
}) : super(key: key);
@override
TransformContainerState createState() {
return new TransformContainerState();
}
}
class TransformContainerState extends State<TransformContainer> {
Matrix4 matrix = Matrix4.identity();
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
GestureDetector(
onTapDown: (details) {
matrix.translate(-details.globalPosition.dx, -details.globalPosition.dy);
matrix.rotateZ(0.174533);
matrix.translate(details.globalPosition.dx, details.globalPosition.dy);
setState(() {});
},
onDoubleTap: () {
setState(() {
matrix = Matrix4.identity();
});
},
child: Transform(
transform: matrix,
alignment: FractionalOffset.topLeft,
child: Container(
color: Colors.black54,
child: Center(
child: Container(
width: 320,
height: 320,
color: Colors.redAccent,
),
),
),
),
),
Positioned(
top: 64.0,
right: 64.0,
child: Container(
color: Colors.pinkAccent,
child: IconButton(
icon: Icon(Icons.refresh),
iconSize: 72.0,
color: Colors.white,
onPressed: () {
setState(() {
matrix = Matrix4.identity();
});
},
),
),
),
],
);
}
}
When you run the code and tap on the screen, the Widget is rotated around the origin. How can I make it rotate around the tap position?
Upvotes: 4
Views: 2624
Reputation: 1304
Set the transform origin as center before applying rotation on the widget;
alignment: FractionalOffset.center
Upvotes: 2