Flutter动画-实现闪烁星星

2,607 阅读1分钟

前言:这篇文章应该说我分享的是最简单的特效:实现星星的闪烁。分享的理由如下:1. 鸽了大家许久的原生学习分享写了也没有分享出来【主要自己没有项目的锤炼不敢误人子弟】,该分享一些文章刷下存在感了😂。 2. 星星闪烁的原理我认为还是有点经验可以借鉴的,故此记录。

原理说明

星星是一张图片素材,我们通过动画实现类似呼吸灯的闪烁效果。两种方式:

  1. 通过中心点放大缩小图片来实现闪烁;
  2. 通过改变透明度来实现,效果也不错。

放大缩小图片实现闪烁

  1. 效果图示 1635669949853.gif

  2. 实现代码

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  late AnimationController animationController;
  late Animation<double> anim;
  AnimationStatus status = AnimationStatus.forward;

  @override
  void initState() {
    super.initState();
    animationController =
        AnimationController(vsync: this, duration: const Duration(seconds: 1));
    // 设置放大倍数,同时循环播放动画
    anim = Tween(begin: 0.5, end: 1.5).animate(animationController)
      ..addListener(() {
        if (animationController.status != AnimationStatus.dismissed &&
            animationController.status != AnimationStatus.completed) {
          status = animationController.status;
        }
        if (animationController.status == AnimationStatus.completed ||
            animationController.status == AnimationStatus.dismissed) {
          status == AnimationStatus.forward
              ? animationController.reverse()
              : animationController.forward();
        }
      });
    animationController.forward();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: AnimatedBuilder(
          animation: anim,
          builder: (context, child) => Transform.scale(
            // 设置动画值为缩放倍数
            scale: anim.value,
            child: Image.asset('assets/star_yellow.png', width: 56, height: 56),
          ),
        ),
      ),
    );
  }
}

通过改变透明度实现闪烁

  1. 效果图示 1635669981619.gif

  2. 实现代码 Flutter自带很多动画组件,透明度可以使用FadeTransition组件,传入动画对象和布局即可。

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Colors.grey,
    appBar: AppBar(
      title: Text(widget.title),
    ),
    body: Center(
      child: FadeTransition(opacity: anim,
        child: Image.asset('assets/star_yellow.png', width: 56, height: 56),
      )
    ),
  );
}

做这个动画的时候,脑海总是想起那首夜空中最亮的星😄 两种效果,你喜欢哪种呢?😋