如何围绕指定的锚点在2D中旋转Container小部件?

bko*_*ash 11 dart flutter

我想对Container小部件执行一个非常简单的2D旋转(包含一些其他小部件.)此小部件将围绕中心的单个固定点旋转,没有变形.

我尝试使用transform财产Matrix4.rotationZ,这在一定程度作品-但锚点是在左上角的角落,而不是在中心.是否有一种简单的方法来指定锚点?

此外,是否有更简单的方法来2D旋转这个不需要Matrix4的小部件?

期望的和实际的转变

var container = new Container (
  child: new Stack (
    children: [
      new Image.asset ( // background photo
        "assets/texture.jpg",
        fit: ImageFit.cover,
      ),
      new Center (
        child: new Container (
          child: new Text (
            "Lorem ipsum",
            style: new TextStyle(
              color: Colors.white,
              fontSize: 42.0,
              fontWeight: FontWeight.w900
            )
          ),
          decoration: new BoxDecoration (
            backgroundColor: Colors.black,
          ),
          padding: new EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 16.0),
          transform: new Matrix4.rotationZ(0.174533), // rotate -10 deg
        ),
      ),
    ],
  ),
  width: 400.0,
  height: 200.0,
);
Run Code Online (Sandbox Code Playgroud)

小智 13

您可以使用 RotatedBox Widget 来旋转任何小部件:

RotatedBox(
    quarterTurns: 3,
    child: Container(
        color:Colors.red
    ),
),
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,您只能旋转四分之一圈,没有分数。 (4认同)

小智 9

在颤振2.2中

使用变换:

Transform(
    transform: Matrix4.rotationZ(...),
    alignment: FractionalOffset.center,
    child: Container(...)
Run Code Online (Sandbox Code Playgroud)

或者在Container中设置transformAlignment值:

Container(
    ...
    transform: Matrix4.rotationZ(...),
    transformAlignment: Alignment.center,
)
Run Code Online (Sandbox Code Playgroud)


bko*_*ash 6

根据Ian的建议,我尝试了以下方法。至少在我有限的测试中,它似乎有效。

容器嵌套在Transform小部件中。使用 alignment可以相对地(即在中心,左上角等)调整变换原点。

var container = new Container (
  child: new Stack (
    children: [
      new Image.asset ( // background photo
        "assets/texture.jpg",
        fit: ImageFit.cover,
      ),
      new Center (
        child: new Transform (
          child: new Container (
            child: new Text (
              "Lorem ipsum",
              style: new TextStyle(
                color: Colors.white,
                fontSize: 42.0,
                fontWeight: FontWeight.w900,
              )
            ),
            decoration: new BoxDecoration (
              backgroundColor: Colors.black,
            ),
            padding: new EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 16.0),              
          ),
          alignment: FractionalOffset.center, // set transform origin
          transform: new Matrix4.rotationZ(0.174533), // rotate -10 deg
        ),
      ),
    ],
  ),
  width: 400.0,
  height: 200.0,
);
Run Code Online (Sandbox Code Playgroud)


Ian*_*son 2

在旋转之前和之后应用平移(往返于支点)。

您可以为自己创建一个小部件来执行此操作,从而同时解决其他问题(隐藏 Matrix4)。