老孟导读:用Flutter实现弹幕功能,轻松实现虎牙、斗鱼的弹幕效果。
先来一张效果图:git
<img src="http://img.laomengit.com/barrage_5.gif" style="zoom:50%;" />程序员
弹幕的实现原理很是简单,即将一条弹幕从左侧平移到右侧,固然咱们要计算弹幕垂直方向上的偏移,否则全部的弹幕都会在一条直线上,相互覆盖。平移代码以下:github
@override void initState() { _animationController = AnimationController(duration: widget.duration, vsync: this) ..addStatusListener((status){ if(status == AnimationStatus.completed){ widget.onComplete(''); } }); var begin = Offset(-1.0, .0); var end = Offset(1.0, .0); _animation = Tween(begin: begin, end: end).animate(_animationController); //开始动画 _animationController.forward(); super.initState(); } @override Widget build(BuildContext context) { return SlideTransition( position: _animation, child: widget.child, ); }
计算垂直方向的偏移:微信
_computeTop(int index, double perRowHeight) { //第几轮弹幕 int num = (index / widget.showCount).floor(); var top; top = (index % widget.showCount) * perRowHeight + widget.padding; if (num % 2 == 1 && index % widget.showCount != widget.showCount - 1) { //第二轮在第一轮2行弹幕中间 top += perRowHeight / 2; } if (widget.randomOffset != 0 && top > widget.randomOffset) { top += _random.nextInt(widget.randomOffset) * 2 - widget.randomOffset; } return top; }
这些准备好后,就是建立一条弹幕了,现建立一条最简单的文字弹幕:dom
Text( text, style: TextStyle(color: Colors.white), );
效果以下:ide
<img src="http://img.laomengit.com/barrage_1.gif" style="zoom:50%;" />字体
建立一条VIP用户的弹幕,其实就是字体变下颜色:动画
Text( text, style: TextStyle(color: Color(0xFFE9A33A)), )
效果以下:ui
<img src="http://img.laomengit.com/barrage_2.gif" style="zoom:50%;" />this
给文字加个圆角背景:
return Center( child: Container( padding: EdgeInsets.only(left: 10, right: 10, top: 3, bottom: 3), decoration: BoxDecoration( color: Colors.red.withOpacity(.8), borderRadius: BorderRadius.circular(50)), child: Text( text, style: TextStyle(color: Colors.white), ), ), );
效果以下:
<img src="http://img.laomengit.com/barrage_3.gif" style="zoom:50%;" />
建立一个送火箭的弹幕:
return Center( child: Container( padding: EdgeInsets.only(left: 10, right: 10, top: 3, bottom: 3), decoration: BoxDecoration( color: Colors.red.withOpacity(.8), borderRadius: BorderRadius.circular(50)), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text( text, style: TextStyle(color: Colors.white), ), Image.asset('assets/images/timg.jpeg',height: 30,width: 30,), Text( 'x $count', style: TextStyle(color: Colors.white, fontSize: 18), ), ], ), ), );
效果以下:
<img src="http://img.laomengit.com/barrage_4.gif" style="zoom:50%;" />
火箭有点丑了,不过这不是重点。
其实实现弹幕效果没有我开始想的那么简单,过程当中也遇到了一些问题,不过好在最终都解决了,献上Github地址:https://github.com/781238222/flutter-do/tree/master/flutter_barrage_sample
若是以为还不错,给个小小的赞。
Github地址:https://github.com/781238222/flutter-do
170+组件详细用法:http://laomengit.com
若是你对Flutter还有疑问或者技术方面的疑惑,欢迎加入Flutter交流群(微信:laomengit)。
同时也欢迎关注个人Flutter公众号【老孟程序员】,公众号首发Flutter的相关内容。
Flutter生态建设离不开你我他,须要你们共同的努力,点赞也是其中的一种,若是文章帮助到了你,但愿点个赞。