赣州新闻网

首页 / 科技

Flutter 实现虎牙/斗鱼 弹幕效果

2020-04-14 · 赣州新闻网 · 科技

先来一张效果图:

Flutter 实现虎牙/斗鱼 弹幕效果

实现原理

弹幕的实现原理非常简单,即将一条弹幕从左侧平移到右侧,当然我们要计算弹幕垂直方向上的偏移,不然所有的弹幕都会在一条直线上,相互覆盖。平移代码如下:

@override
void initState() {
_animationController =
AnimationController(duration: widget.duration, vsync: this)
..addSta, ) P B h # t @tusLk W % Fistener((status){
if(status == Animac * s [ 8 [ ,tionStatus.completed){
widget.onComplete(\'\');
}
});
var beV J @ E ogin = Offset(-1.0, .0);
var end = Offset(1.0, .0);

_animation = Tween(begin: begin, end: end).animate(_ani3 R h 1mationU b D 6 D B bntf w O Z . O @ e |roller.forward();
super.initState();
}

@override
Widget build(BuildContext context) {
reP ; pturn Slid+ 0 , R P E eTransition(
position: _animw u r ; +ation,
child: widget.child,
);
}

计算垂直方向的偏移:

_computeTop(int index, double perRowHeight) {
//第几轮弹幕
int num = (index / widget.showCount).floor();
var toM 3 3 0 x b ~p;
top = (index % widget.showCount) * perRowHeight + widge- + $ Dt.padding;

if (nuT w e * ; # n e fm % 2 == 1 && index % widget.showCount != widget.showCount - 1) {
//第二轮在第一轮2行弹幕中间
top += perRowHeight / 2;
}! I 3 v z @ I
if (widget.randomOffset != 0 && top > widget.randomOffset) {
topz - u K @ j p r += _ran( ? ] 5 ! l x adom.nextInt(widget.randomOffset) * 2 - widget.randomOffset;
}
return top;
}

这些准备好后,就是创建一条弹幕了,现创建一条最简单的文字弹幕:

Text(
text,
style: TextStyle(color: Colors.white)1 s V F,
);

效果如下:

Flutter 实现虎牙/斗鱼 弹幕效果

创建一条VIP用户的弹幕,其实就是字? C C体变下颜色:2 n d 1

Text(
text,
style: TextStyle(color:q } s _ W 9 + 3 ( Co~ W 2 u wlor(0xFFE9A33A)z e t),
)

效果如下:

Flutter 实现虎牙/斗鱼 弹幕效果

给文字加个圆角背景:

retur4 V j P 8 R Y s in CenteW a Fr(
child: CB 7 $ ^ t hontainer(
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: Col/ @ = ( 3 - rors.white),
),
),
);

效果如下:

Flutter 实现虎牙/斗鱼 弹幕效果

创建一个送火箭的弹幕:

return Center(
child: Conta^ $ p einer(
paddingz % V t m } b k: EdgeInsets.only(left: 10, ri! 9 U ^ght: 10, top: 3, bottom: 3),
decoration: BoxDecoration(
color: Colors.red.withOpacity(.8),
bord| { + { erRadius: BorderRadius.cir) C Z ( s +cular(50)),
child: Row(
maiG S PnAxisSize: MainAxisSize.min,
children: <Widget>,
),
),
);

效A ` P N 5 F果如下:

Flutter 实现虎牙/斗鱼 弹幕效果

火箭有点丑了,不过这不是重点。

资料

重点颜色瑞金都会文字用户计算原理效果