温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Flutter如何实现虎牙/斗鱼弹幕功能

发布时间:2020-08-04 10:09:49 来源:亿速云 阅读:148 作者:小猪 栏目:移动开发

这篇文章主要为大家展示了Flutter如何实现虎牙/斗鱼弹幕功能,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。

先来一张效果图:

Flutter如何实现虎牙/斗鱼弹幕功能

实现原理

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

@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;
}

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

Text(
 text,
 style: TextStyle(color: Colors.white),
);

效果如下:

Flutter如何实现虎牙/斗鱼弹幕功能

创建一条VIP用户的弹幕,其实就是字体变下颜色:

Text(
 text,
 style: TextStyle(color: Color(0xFFE9A33A)),
)

效果如下:

Flutter如何实现虎牙/斗鱼弹幕功能

给文字加个圆角背景:

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),
 ),
 ),
);

效果如下:

Flutter如何实现虎牙/斗鱼弹幕功能

创建一个送火箭的弹幕:

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),
  ),
  ],
 ),
 ),
);

效果如下:

Flutter如何实现虎牙/斗鱼弹幕功能

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

以上就是关于Flutter如何实现虎牙/斗鱼弹幕功能的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI