📅  最后修改于: 2023-12-03 15:12:54.356000             🧑  作者: Mango
颤振块旋转是一种常用的动画效果,通过改变一个元素的大小和位置,使得它看起来像是在颤动和旋转。在 Dart 中,可以使用 Tween 和 AnimationController 类来实现这种效果。
AnimationController 控制动画的状态,包括开始、停止、暂停等。在创建 AnimationController 时,需要指定动画的时长和 TickerProvider(通常使用 vsync)。
final AnimationController _controller = AnimationController(
duration: Duration(seconds: 1),
vsync: this,
);
Tween 定义了动画的取值范围,它确定了动画应该如何渲染值。在颤振块旋转效果中,需要创建两个 Tween,分别对应于旋转和缩放的变化。
final Animation<double> _rotateAnimation = Tween<double>(
begin: 0.0,
end: 1.0,
).animate(_controller);
final Animation<double> _scaleAnimation = Tween<double>(
begin: 100.0,
end: 200.0,
).animate(_controller);
通过监听 _controller 的状态变化来执行动画效果。在每个状态改变时都需要调用 setState 方法重新构建 UI。
_controller.addListener(() {
setState(() {});
});
在 UI 中使用 Transform Widget 来执行旋转和缩放的变化。可以使用 Matrix4.rotationZ 方法创建旋转的变换矩阵,使用 Matrix4.diagonal3Values 方法创建缩放的变换矩阵。
Transform.rotate(
angle: _rotateAnimation.value * pi * 2.0,
child: Transform.scale(
scale: _scaleAnimation.value / 100.0,
child: Container(
width: 200.0,
height: 200.0,
color: Colors.blue,
),
),
)
import 'package:flutter/material.dart';
import 'dart:math';
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
duration: Duration(seconds: 1),
vsync: this,
);
late final Animation<double> _rotateAnimation =
Tween<double>(begin: 0.0, end: 1.0).animate(_controller);
late final Animation<double> _scaleAnimation =
Tween<double>(begin: 100.0, end: 200.0).animate(_controller);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
_controller.repeat();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Transform.rotate(
angle: _rotateAnimation.value * pi * 2.0,
child: Transform.scale(
scale: _scaleAnimation.value / 100.0,
child: Container(
width: 200.0,
height: 200.0,
color: Colors.blue,
),
),
),
),
);
}
}
通过 AnimationController 和 Tween 来创建动画效果,可以轻松地实现颤振块旋转效果。该效果不仅可以增加应用程序的吸引力,而且还可以为用户提供更加愉悦的使用体验。