美文网首页
flutter 中的图片旋转

flutter 中的图片旋转

作者: FlowYourHeart | 来源:发表于2023-05-29 16:50 被阅读0次

    看到旋转、移动等字眼,不难想到动画。不错这里就是动画。先看效果

    旋转.gif
    
    class MyHomePage extends StatefulWidget {
     MyHomePage({Key? key, required this.title}) : super(key: key);
    
     final String title;
    
     @override
     _MyHomePageState createState() => _MyHomePageState();
    }
    
    //几乎所有的controller控制器 都需要mixin 去做检讨 这里因为只有一个controller 所以用的SingleTickerProviderStateMixin
    //如果是多个动画 则需要用TickerProviderStateMixin
    class _MyHomePageState extends State<MyHomePage>
       with SingleTickerProviderStateMixin{
     late AnimationController _controller;
     @override
     void initState() {
       super.initState();
       _controller = AnimationController(
           vsync: this,
           //动画时长 这里也就是旋转一圈所用时间 也可以理解为动画速度
           duration: Duration(seconds: 1),
           animationBehavior:AnimationBehavior.preserve)
         ..addStatusListener((AnimationStatus status) {
           //动画完成后继续动画
           //forward 相当于start 开始动画
           //因为动画结束时 我们已经在下面重新给了初始值 所以不会有异样
           if (status == AnimationStatus.dismissed) {
             _controller.forward();
           } 
         })
         ..addListener(() {
           setState(() {
             //为了动画能不停重复 这里在动画完成时 置初始位置
             //如果不这样做处理 value永远是1.0 即使forward了也不会有动画效果(其实是在动的,只是都在1.0的地方动)
             if(_controller.value==1.0){
               _controller.value = 0.0;
             }
           });
         });
    
     }
    
    @override
     void dispose() {
       _controller.dispose();
       super.dispose();
     }
    
     @override
     Widget build(BuildContext context) {
      
       return Scaffold(
         appBar: AppBar(
           title: Text(widget.title),
         ),
         body: Center(
             child: _buildRotationTransition()),
         floatingActionButton: FloatingActionButton(
           onPressed: () {
             if(_controller.isAnimating){
               _controller.stop();
             }else {
               _controller.forward();
             }
             
           },
           tooltip: 'Increment',
           child: Icon(Icons.add),
         ),
       );
     }
    
     //中间图片旋转的组件
     Widget _buildRotationTransition() {
       return Container(
         child: RotationTransition(
           //设置动画的旋转中心
           alignment: Alignment.center,
           //动画控制器
           turns: _controller,
           //将要执行动画的子view
           child: Container(
             width: 130,
             height: 130,
           //圆形剪切
             child: ClipOval(
               child: Image.network(
                   "https://img1.baidu.com/it/u=898692534,2766260827&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1685552400&t=40fae7e2bc640251424efe4128c0d49f"),
             ),
           ),
         ),
       );
     }
    }
    
    
    

    相关文章

      网友评论

          本文标题:flutter 中的图片旋转

          本文链接:https://www.haomeiwen.com/subject/eewjedtx.html