当前位置: 移动技术网 > IT编程>移动开发>Android > Flutter 实现虎牙/斗鱼 弹幕功能

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

2020年06月23日  | 移动技术网IT编程  | 我要评论

黄炎培简介,折纸网,诡新娘 电影

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

效果如下:

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

text(
 text,
 style: textstyle(color: color(0xffe9a33a)),
)

效果如下:

给文字加个圆角背景:

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

效果如下:

创建一个送火箭的弹幕:

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

效果如下:

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

其实实现弹幕效果没有我开始想的那么简单,过程中也遇到了一些问题,不过好在最终都解决了,献上github地址:

如果觉得还不错,给个小小的赞。

交流

github地址:

170+组件详细用法:

总结

到此这篇关于flutter 实现虎牙/斗鱼 弹幕功能的文章就介绍到这了,更多相关flutter 实现虎牙斗鱼 弹幕内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网