如何使用Flutter中的手势围绕焦点旋转小部件?

时间:2019-01-09 18:59:10

标签: dart flutter

在Flutter中,我可以使用“变换”小部件来旋转小部件。但是,旋转是围绕“变换”窗口小部件属性中指定的原点,而不是围绕当前焦点。

我尝试通过平移到焦点,旋转然后平移回原点来修改矩阵。

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();
                });
              },
            ),
          ),
        ),
      ],
    );
  }
}

运行代码并在屏幕上点击时,窗口小部件将绕原点旋转。如何使其围绕点击位置旋转?

1 个答案:

答案 0 :(得分:1)

在对窗口小部件进行旋转之前,将变换原点设置为 center

alignment: FractionalOffset.center