【问题标题】:How do I rotate something 15 degrees in Flutter?如何在 Flutter 中旋转 15 度?
【发布时间】:2017-10-31 17:53:36
【问题描述】:

Flutter 文档展示了一个将“div”旋转 15 度的示例,适用于 HTML/CSS 和 Flutter 代码:

Flutter 代码是:

var container = new Container( // gray box
  child: new Center(
    child:  new Transform(
      child:  new Text(
        "Lorem ipsum",
      ),
      alignment: FractionalOffset.center,
      transform: new Matrix4.identity()
        ..rotateZ(15 * 3.1415927 / 180),
    ), 
  ),
);

相关部分为new Transformalignment: FractionalOffset.centertransform: new Matrix4.identity()..rotateZ(15 * 3.1415927 / 180)

我很好奇,有没有更简单的方法在 Flutter 中旋转 Container? “15度”的情况有简写吗?

谢谢!

【问题讨论】:

  • 一个答案都行不通!有什么解决办法吗?

标签: dart flutter


【解决方案1】:

在移动应用程序中,我认为很少有事情开始旋转 15 度然后永远停留在那里。因此,如果您打算随着时间的推移调整旋转,这可能就是为什么 Flutter 对旋转的支持更好的原因。

感觉有点矫枉过正,但是 RotationTransitionAlwaysStoppedAnimation 可以完全满足您的需求。

new RotationTransition(
  turns: new AlwaysStoppedAnimation(15 / 360),
  child: new Text("Lorem ipsum"),
)

如果您想旋转 90、180 或 270 度,可以使用 RotatedBox

new RotatedBox(
  quarterTurns: 1,
  child: new Text("Lorem ipsum")
)

【讨论】:

  • 您知道使用 RotationTransition 与 Transform 对性能有何影响吗?
  • 性能差异应该可以忽略不计。如果您深入了解 RotationTransition 的代码,则几乎完全相同。唯一的区别是会构造一些额外的对象(RotationTransition 和 AlwaysStoppedAnimation),这在 Dart 中非常便宜。因为动画永远不会改变,RotationTransition 只会自己构建一次。
  • 注意:RotatedBox 小部件四分之一相当于 0、90、180、270 度,遗憾的是不适合其他角度(例如 15° 或 45°)
【解决方案2】:

您可以使用Transform.rotate 来旋转您的小部件。我使用Text 并将其旋转了 45˚ (π/4)

例子:

import 'dart:math' as math;

Transform.rotate(
  angle: -math.pi / 4,
  child: Text('Text'),
)

【讨论】:

    【解决方案3】:

    如果您正在使用画布 (as in a CustomPaint widget),您可以像这样旋转 15 度:

    import 'dart:math' as math;
    
    class MyPainter extends CustomPainter {
      @override
      void paint(Canvas canvas, Size size) {
        canvas.save();
    
        // rotate the canvas
        final degrees = 15;
        final radians = degrees * math.pi / 180;
        canvas.rotate(radians);
    
        // draw the text
        final textStyle = TextStyle(color: Colors.black, fontSize: 30);
        final textSpan = TextSpan(text: 'Hello, world.', style: textStyle);
        TextPainter(text: textSpan, textDirection: TextDirection.ltr)
          ..layout(minWidth: 0, maxWidth: size.width)
          ..paint(canvas, Offset(0, 0));
    
        canvas.restore();
      }
    
      @override
      bool shouldRepaint(CustomPainter old) {
        return false;
      }
    }
    

    但是,如果您正在做一些简单的事情,那么我会按照其他答案的建议使用 RotatedBoxTransform.rotate

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-26
      • 2020-08-22
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多