老孟導讀:用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生態建設離不開你我他,須要你們共同的努力,點贊也是其中的一種,若是文章幫助到了你,但願點個贊。