相信大家看视频的时候都会有弹幕效果,这似乎已经成为视频软件的标配,接下来让我们来看看如何实现这个弹幕效果。
一.弹幕效果分析
我可以看到,弹幕效果是在屏幕上方飘过,即从屏幕外一端出现,一直在屏幕中飘动至屏幕另一端,我们将其实现逻辑进行分解如下:
1.一个viewGroup中包含多个textView
2.textView包含平移动画
经过分解发现其逻辑一点也不复杂,分析完
二.实现
上面我们分析了自定义弹幕效果View的逻辑:
这里我们让我们自定义的的BarrageView继承RelateLayout,并实现onLayout方法。
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int childCount = this.getChildCount();
for(int i = 0; i < childCount; i++){
final View view = getChildAt(i);
if (view != null){
RelativeLayout.LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (lp.leftMargin <= 0){
if(mDirection == FROM_RIGNG_TO_LEFT){
view.layout(mScreenWidth,lp.topMargin,mScreenWidth+view.getMeasuredWidth(),
lp.topMargin+view.getMeasuredHeight());
}else if(mDirection == FROM_LEFT_TO_RIGHT){
view.layout(-view.getMeasuredWidth(),lp.topMargin,0,
lp.topMargin+view.getMeasuredHeight());
}
}
}
}
}
这里很多人可能会问为什么是实现onLayout方法,我们的BarrageView继承了RelateLayout,即继承了一个viewGroup,而飘屏的弹幕均属于这个viewGroup的子View,我们的弹幕效果要实现必须在我们需要的时候往这个BarrageView中添加一个子view,添加子view我们就必须要为其指定在父控件中的位置。而每当我们像BarrageView中加入一个子view,就会执行其onLayout方法,所以我们最终就在onLayout中确定子view的初始位置
从代码中我们可以看到这边我支持了两个方向,从左到右(
FROM_LEFT_TO_RIGHT
)和从右到左(
FROM_RIGNG_TO_LEFT
),这里我们分析从右到左,毕竟目前较多的软件都是从右到左飘屏
view.layout(mScreenWidth,lp.topMargin,mScreenWidth+view.getMeasuredWidth(),
lp.topMargin+view.getMeasuredHeight());