如何在图像内的任意点上旋转(并可能设置动画)图像?

时间:2017-04-21 19:43:48

标签: dart flutter

我正在使用Flutter,我希望图像在我定义的点上旋转。例如,我想让图像为其右上角的旋转(向下摆动)设置动画。我该怎么做?

1 个答案:

答案 0 :(得分:13)

这是一个使用FractionalOffset类来指定旋转点的解决方案。

如果您不想动画,Transform会做您想要的。

    return new Transform(
      transform: new Matrix4.rotationZ(math.PI),
      alignment: FractionalOffset.bottomRight,
      child: child,
    );

如果你想要制作动画,RotationTransition几乎可以做你想要的,除了对齐是不可配置的。您可以创建自己的可配置版本:

import 'dart:ui';
import 'dart:math' as math;
import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
      title: "Rotation Demo",
      home: new RotateDemo(),
  ));
}

/// Animates the rotation of a widget around a pivot point.
class PivotTransition extends AnimatedWidget {
  /// Creates a rotation transition.
  ///
  /// The [turns] argument must not be null.
  PivotTransition({
    Key key,
    this.alignment: FractionalOffset.center,
    @required Animation<double> turns,
    this.child,
  }) : super(key: key, listenable: turns);

  /// The animation that controls the rotation of the child.
  ///
  /// If the current value of the turns animation is v, the child will be
  /// rotated v * 2 * pi radians before being painted.
  Animation<double> get turns => listenable;

  /// The pivot point to rotate around.
  final FractionalOffset alignment;

  /// The widget below this widget in the tree.
  final Widget child;

  @override
  Widget build(BuildContext context) {
    final double turnsValue = turns.value;
    final Matrix4 transform = new Matrix4.rotationZ(turnsValue * math.PI * 2.0);
    return new Transform(
      transform: transform,
      alignment: alignment,
      child: child,
    );
  }
}

class RotateDemo extends StatefulWidget {
  State createState() => new RotateDemoState();
}

class RotateDemoState extends State<RotateDemo> with TickerProviderStateMixin {
  AnimationController _animationController;

  @override initState() {
    super.initState();
    _animationController = new AnimationController(
      duration: const Duration(milliseconds: 3000),
      vsync: this,
    )..repeat();
  }

  @override dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body:
          new Center(
            child: new PivotTransition(
              turns: _animationController,
              alignment: FractionalOffset.bottomRight,
              child: new Container(
                decoration: new BoxDecoration(backgroundColor: Colors.grey.shade200),
                width: 100.0,
                child: new FlutterLogo(style: FlutterLogoStyle.horizontal),
              ),
            ),
          ),
    );
  }
}

此示例将Flutter徽标旋转到其右下角。

enter image description here

如果您有冒险精神,可以向Flutter发送拉取请求,以使RotationTransition的路线可配置。