Как повернуть изображение с помощью Flutter AnimationController и Transform?

У меня есть изображение звезды png, и мне нужно повернуть звезду с помощью Flutter AnimationController и Transformer. Мне не удалось найти никаких документов или примеров для анимации вращения изображения.

Есть идеи Как повернуть изображение с помощью Flutter AnimationController и Transform?

ОБНОВИТЬ:

class _MyHomePageState extends State<MyHomePage>  with TickerProviderStateMixin {

  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(
      vsync: this,
      duration: new Duration(milliseconds: 5000),
    );
    animationController.forward();
    animationController.addListener(() {
      setState(() {
        if (animationController.status == AnimationStatus.completed) {
          animationController.repeat();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      alignment: Alignment.center,
      color: Colors.white,
      child: new AnimatedBuilder(
        animation: animationController,
        child: new Container(
          height: 80.0,
          width: 80.0,
          child: new Image.asset('images/StarLogo.png'),
        ),
        builder: (BuildContext context, Widget _widget) {
          return new Transform.rotate(
            angle: animationController.value,
            child: _widget,
          );
        },
      ),
    );
  }
}

Не могли бы вы прошить код с инициализацией animationRotate?

Andrey Turkovsky 12.12.2018 15:50

Я обновляю свой код. Проблема в том, что он никогда не вращается на 360 градусов. Он вращается примерно на 200 или около того и начинается заново, и я вижу пробел, который он перерисовывает. Возникла проблема с поворотом на 360 градусов, и когда я останавливаюсь, мне нужно повторить без задержки, чтобы я мог продолжить вращение, остановку белого цвета ...

Nick 13.12.2018 10:30

Обновил ответ

Andrey Turkovsky 13.12.2018 11:04
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
31
3
44 495
8
Перейти к ответу Данный вопрос помечен как решенный

Ответы 8

Ответ принят как подходящий

Вот мой пример вращающегося изображения. Не знаю - но, может, тебе подходит

AnimationController rotationController;

@override
void initState() {
  rotationController = AnimationController(duration: const Duration(milliseconds: 500), vsync: this);
  super.initState();
}
//...
RotationTransition(
  turns: Tween(begin: 0.0, end: 1.0).animate(rotationController),
  child: ImgButton(...)
//...
rotationController.forward(from: 0.0); // it starts the animation

UPD - как решить проблему с Transform.rotate

В вашем случае все работает именно так, как вы написали - изображение поворачивается от 0,0 до 1,0 (это параметры по умолчанию для AnimationController). Для полного круга необходимо установить верхний параметр на 2 * pi (из пакета math).

import 'dart:math';
//...
animationController = AnimationController(vsync: this, duration: Duration(seconds: 5), upperBound: pi * 2);

как мы можем добавить сюда кривые

codeboi 15.05.2021 10:07

@codeboi вот ответ stackoverflow.com/a/55365126/7130820

Andrey Turkovsky 17.05.2021 08:56

Полный пример (нулевой безопасный):

Demo Screenshot

Нажатие «go» заставляет значок звездочки вращаться, пока вы не нажмете «стоп».

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
      duration: const Duration(milliseconds: 5000),
      vsync: this,
    );
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Demo"),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            RotationTransition(
              turns: Tween(begin: 0.0, end: 1.0).animate(_controller),
              child: Icon(Icons.stars),
            ),
            ElevatedButton(
              child: Text("go"),
              onPressed: () => _controller.forward(),
            ),
            ElevatedButton(
              child: Text("reset"),
              onPressed: () => _controller.reset(),
            ),
          ],
        ),
      ),
    );
  }
}

Пошаговое руководство:

Во-первых, позвольте вашему классу состояния виджета реализовать SingleTickerProviderStateMixin.

Во-вторых, определите AnimationController и не забудьте утилизировать его. Если вы еще не используете нулевой безопасный режим, удалите ключевое слово late.

late AnimationController _controller;

@override
void initState() {
  _controller = AnimationController(
    duration: const Duration(milliseconds: 5000),
    vsync: this,
  );
  super.initState();
}

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

Затем оберните ваш Widget в RotationTransition.

RotationTransition(
  turns: Tween(begin: 0.0, end: 1.0).animate(_controller),
  child: Icon(Icons.stars),
),

Наконец, вызовите методы на AnimationController для запуска / остановки анимации.

  • Запустите анимацию один раз, используйте .forward
  • Прокрутите анимацию, используйте .repeat
  • Немедленно остановитесь, используйте .stop
  • Остановите и верните его в исходное положение, используйте .reset
  • Остановите и выполните анимацию до значения поворота, используйте .animateTo

Здесь я поворачиваю 3 изображения одновременно ... изображения, сохраненные в папке с ресурсами ... если вы хотите, вы также можете использовать сетевые изображения ... я здесь вращаю 3 изображения на 3 скоростях ...

import 'package:flutter/material.dart';
import 'package:fynd/services/auth.dart';
import 'dart:async';
import 'package:fynd/services/cons.dart';

class SplashScreen extends StatefulWidget {
  _SplashScreen createState() => new _SplashScreen();
}

class _SplashScreen extends State<StatefulWidget>
    with SingleTickerProviderStateMixin {
  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 5),
    );

    animationController.repeat();
  }

  @override
  Widget build(BuildContext context) {

    return new Container(
      alignment: Alignment.center,
      color: Colors.white,
      child: new AnimatedBuilder(
        animation: animationController,
        child: new Container(
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('assets/images/splash_circle3.png'))),
          child: new AnimatedBuilder(
            animation: animationController,
            child: new Container(
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage('assets/images/splash_circle2.png'))),
              child: new AnimatedBuilder(
                  animation: animationController,
                  child: Container(
                      child: Container(
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage(
                                'assets/images/splash_circle1.png'))),
                  )),
                  builder: (BuildContext context, Widget _widget) {
                    return new Transform.rotate(
                      angle: animationController.value * 4,
                      child: _widget,
                    );
                  }),
            ),
            builder: (BuildContext context, Widget _widget) {
              return new Transform.rotate(
                angle: animationController.value * 5,
                child: _widget,
              );
            },
          ),
        ),
        builder: (BuildContext context, Widget _widget) {
          return new Transform.rotate(
            angle: animationController.value * 6,
            child: _widget,
          );
        },
      ),
    );
  }
}

здесь я помещаю анимированный строитель в стек. затем вы можете анимировать изображение с поворотом вправо (по часовой стрелке) и поворотом влево (против часовой стрелки).

import 'package:flutter/material.dart';
import 'package:fynd/services/auth.dart';
import 'dart:async';
import 'package:fynd/services/cons.dart';

class SplashScreen extends StatefulWidget {
  _SplashScreen createState() => new _SplashScreen();
}

class _SplashScreen extends State<StatefulWidget>
    with SingleTickerProviderStateMixin {
  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 5),
    );

    animationController.repeat();

  }

  @override
  Widget build(BuildContext context)

    return new Container(
      alignment: Alignment.center,
      color: Colors.white,

      child: new Stack(children: <Widget>[

        new AnimatedBuilder(
          animation: animationController,
          child :Container(
            decoration: BoxDecoration(
                image: DecorationImage(image: AssetImage('assets/images/splash_circle3.png'),fit: BoxFit.cover)),

          ),
          builder: (BuildContext context, Widget _widget) {
            return new Transform.rotate(
              angle: animationController.value * 10,
              child: _widget,
            );
          },
        ),

       new AnimatedBuilder(
        animation: animationController,
        child: Container(
          decoration: BoxDecoration(
              image: DecorationImage(image: AssetImage('assets/images/splash_circle2.png'),fit: BoxFit.cover)),

        ),
        builder: (BuildContext context, Widget _widget) {
          return new Transform.rotate(
            angle: -animationController.value * 10,
            child: _widget,
          );
        },
       ),

        new AnimatedBuilder(
            animation: animationController,
           child: Container(
              decoration: BoxDecoration(
                  image: DecorationImage(image: AssetImage('assets/images/splash_circle1.png'), fit: BoxFit.cover)),
            ),
            builder: (BuildContext context, Widget _widget) {
              return new Transform.rotate(
                angle: animationController.value * 10,
                child: _widget,
              );
            }),

      ],),
    );
  }
}

Снимок экрана (Null Safe)


Полный код:

import 'dart:math' as math;

class _FooPageState extends State<FooPage> with SingleTickerProviderStateMixin{
  late final AnimationController _controller = AnimationController(vsync: this, duration: Duration(seconds: 2))..repeat();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: AnimatedBuilder(
          animation: _controller,
          builder: (_, child) {
            return Transform.rotate(
              angle: _controller.value * 2 * math.pi,
              child: child,
            );
          },
          child: FlutterLogo(size: 200),
        ),
      ),
    );
  }
}

Как повернуть это по оси Y, есть идеи?

who-aditya-nawandar 22.09.2021 16:43

    _controller = AnimationController(duration: const Duration(seconds: 3), vsync: this);
    _animation = Tween(begin: 0.0, end: 250.0).animate(_controller)
      ..addListener(() {
        setState(() {});
      })
      ..addStatusListener((state) {
        if (state == AnimationStatus.completed) {
          print("complete");
        }
      });
    _controller.forward();

    new Future.delayed(
        const Duration(seconds: 5),
            () => Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => SignScreen()),
        ));    
class _MyHomePageState extends State<MyHomePage>  with TickerProviderStateMixin {

  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(
      vsync: this,
      duration: new Duration(milliseconds: 5000),
    );
    animationController.repeat();

  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      alignment: Alignment.center,
      color: Colors.white,
      child: RotationTransition(
              child: Icon(Icons.refresh),
              turns: controller,
            )
    );
  }
}

full example just call ImageAnimateRotate( your widget )

class ImageAnimateRotate extends StatefulWidget {
  final Widget child;
  const ImageAnimateRotate({Key? key, required this.child}) : super(key: key);

  @override
  _ImageAnimateRotateState createState() => _ImageAnimateRotateState();
}

class _ImageAnimateRotateState extends State<ImageAnimateRotate> with SingleTickerProviderStateMixin {
  late final AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: Duration(seconds: 20))..repeat();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: AnimatedBuilder(
        animation: _controller,
        builder: (_, child) {
          return Transform.rotate(
            angle: _controller.value * 2 * math.pi,
            child: child,
          );
        },
        child: widget.child,
      ),
    );
  }
}

Другие вопросы по теме