Android直播中弹幕效果实现

       在B站或者其他视频网站看视频时,常常会打开弹幕效果,边看节目边看大家的吐槽。弹幕看起来很有意思,今天我们就来实现一个简单的弹幕效果。


       从直观上,弹幕效果就是在一个ViewGroup上增加一些View,然后让这些View移动起来。所以,整体的实现思路大概是这样的:

1、定义一个RelativeLayout,在里面动态添加TextView。

2、这些TextView的字体大小、颜色、移动速度、初始位置都是随机的。

3、将TextView添加到RelativeLayout的右边缘,每隔一段时间添加一个。

4、对每个TextView做平移动画,使得TextView从右向左移动。

5、当TextView从左边移动出屏幕,将TextView从RelativeLayout中移除。

       有了思路下面就来看具体的代码。

       首先定义BarrageItem,用来存储每一个弹幕项的相关信息,包括字体内容、字体大小颜色、移动速度、垂直方向的位置、字体占据的宽度等。

  1. public class BarrageItem {  
  2.     public TextView textView;  
  3.     public int textColor;  
  4.     public String text;  
  5.     public int textSize;  
  6.     public int moveSpeed;//移动速度  
  7.     public int verticalPos;//垂直方向显示的位置  
  8.     public int textMeasuredWidth;//字体显示占据的宽度  
  9. }  
public class BarrageItem {
    public TextView textView;
    public int textColor;
    public String text;
    public int textSize;
    public int moveSpeed;//移动速度
    public int verticalPos;//垂直方向显示的位置
    public int textMeasuredWidth;//字体显示占据的宽度
}

       然后定义BarrageView,由于弹幕的字体颜色大小和移动速度都是随机的,需要定义最大最小值来限定它们的范围,然后通过产生随机数来设置它们在这个范围内的值。另外还需要定义弹幕的文本内容,这里是直接写死的一些固定值。

  1.     private Context mContext;  
  2.     private BarrageHandler mHandler = new BarrageHandler();  
  3.     private Random random = new Random(System.currentTimeMillis());  
  4.     private static final long BARRAGE_GAP_MIN_DURATION = 1000;//两个弹幕的最小间隔时间  
  5.     private static final long BARRAGE_GAP_MAX_DURATION = 2000;//两个弹幕的最大间隔时间  
  6.     private int maxSpeed = 10000;//速度,ms  
  7.     private int minSpeed = 5000;//速度,ms  
  8.     private int maxSize = 30;//文字大小,dp  
  9.     private int minSize = 15;//文字大小,dp  
  10.   
  11.     private int totalHeight = 0;  
  12.     private int lineHeight = 0;//每一行弹幕的高度  
  13.     private int totalLine = 0;//弹幕的行数  
  14.     private String[] itemText = {“是否需要帮忙”“what are you 弄啥来”“哈哈哈哈哈哈哈”“抢占沙发。。。。。。”“************”“是否需要帮忙”,“我不会轻易的狗带”“嘿嘿”“这是我见过的最长长长长长长长长长长长的评论”};  
  15.     private int textCount;  
  16. //    private List<BarrageItem> itemList = new ArrayList<BarrageItem>();  
  17.   
  18.     public BarrageView(Context context) {  
  19.         this(context, null);  
  20.     }  
  21.   
  22.     public BarrageView(Context context, AttributeSet attrs) {  
  23.         this(context, attrs, 0);  
  24.     }  
  25.   
  26.     public BarrageView(Context context, AttributeSet attrs, int defStyleAttr) {  
  27.         super(context, attrs, defStyleAttr);  
  28.         mContext = context;  
  29.         init();  
  30.     }  
    private Context mContext;
    private BarrageHandler mHandler = new BarrageHandler();
    private Random random = new Random(System.currentTimeMillis());
    private static final long BARRAGE_GAP_MIN_DURATION = 1000;//两个弹幕的最小间隔时间
    private static final long BARRAGE_GAP_MAX_DURATION = 2000;//两个弹幕的最大间隔时间
    private int maxSpeed = 10000;//速度,ms
    private int minSpeed = 5000;//速度,ms
    private int maxSize = 30;//文字大小,dp
    private int minSize = 15;//文字大小,dp

    private int totalHeight = 0;
    private int lineHeight = 0;//每一行弹幕的高度
    private int totalLine = 0;//弹幕的行数
    private String[] itemText = {"是否需要帮忙", "what are you 弄啥来", "哈哈哈哈哈哈哈", "抢占沙发。。。。。。", "************", "是否需要帮忙","我不会轻易的狗带", "嘿嘿", "这是我见过的最长长长长长长长长长长长的评论"};
    private int textCount;
//    private List<BarrageItem> itemList = new ArrayList<BarrageItem>();

    public BarrageView(Context context) {
        this(context, null);
    }

    public BarrageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BarrageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

       如果弹幕显示的垂直位置是随机的,就会出现垂直方向上弹幕重叠的情况,所以需要根据高度对垂直方向按照弹幕高度的最大值等分,然后让弹幕在这些指定的垂直位置随机分布。这个值在onWindowFocusChanged里计算,因为在这个方法中通过View的getMeasuredHeight()得到的高度不为空。

  1. @Override  
  2. public void onWindowFocusChanged(boolean hasWindowFocus) {  
  3.     super.onWindowFocusChanged(hasWindowFocus);  
  4.     totalHeight = getMeasuredHeight();  
  5.     lineHeight = getLineHeight();  
  6.     totalLine = totalHeight / lineHeight;  
  7. }  
    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        totalHeight = getMeasuredHeight();
        lineHeight = getLineHeight();
        totalLine = totalHeight / lineHeight;
    }

       通过Handler的sendEmptyMessageDelayed每隔随机的时间产生一个弹幕项。下面的代码设置弹幕项的属性。

  1. class BarrageHandler extends Handler {  
  2.     @Override  
  3.     public void handleMessage(Message msg) {  
  4.         super.handleMessage(msg);  
  5.         generateItem();  
  6.         //每个弹幕产生的间隔时间随机  
  7.         int duration = (int) ((BARRAGE_GAP_MAX_DURATION - BARRAGE_GAP_MIN_DURATION) * Math.random());  
  8.         this.sendEmptyMessageDelayed(0, duration);  
  9.     }  
  10. }  
  11.   
  12. private void generateItem() {  
  13.     BarrageItem item = new BarrageItem();  
  14.     String tx = itemText[(int) (Math.random() * textCount)];  
  15.     int sz = (int) (minSize + (maxSize - minSize) * Math.random());  
  16.     item.textView = new TextView(mContext);  
  17.     item.textView.setText(tx);  
  18.     item.textView.setTextSize(sz);  
  19.     item.textView.setTextColor(Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256)));  
  20.     item.textMeasuredWidth = (int) getTextWidth(item, tx, sz);  
  21.     item.moveSpeed = (int) (minSpeed + (maxSpeed - minSpeed) * Math.random());  
  22.     if (totalLine == 0) {  
  23.         totalHeight = getMeasuredHeight();  
  24.         lineHeight = getLineHeight();  
  25.         totalLine = totalHeight / lineHeight;  
  26.     }  
  27.     item.verticalPos = random.nextInt(totalLine) * lineHeight;  
  28.     showBarrageItem(item);  
  29. }  
    class BarrageHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            generateItem();
            //每个弹幕产生的间隔时间随机
            int duration = (int) ((BARRAGE_GAP_MAX_DURATION - BARRAGE_GAP_MIN_DURATION) * Math.random());
            this.sendEmptyMessageDelayed(0, duration);
        }
    }

    private void generateItem() {
        BarrageItem item = new BarrageItem();
        String tx = itemText[(int) (Math.random() * textCount)];
        int sz = (int) (minSize + (maxSize - minSize) * Math.random());
        item.textView = new TextView(mContext);
        item.textView.setText(tx);
        item.textView.setTextSize(sz);
        item.textView.setTextColor(Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        item.textMeasuredWidth = (int) getTextWidth(item, tx, sz);
        item.moveSpeed = (int) (minSpeed + (maxSpeed - minSpeed) * Math.random());
        if (totalLine == 0) {
            totalHeight = getMeasuredHeight();
            lineHeight = getLineHeight();
            totalLine = totalHeight / lineHeight;
        }
        item.verticalPos = random.nextInt(totalLine) * lineHeight;
        showBarrageItem(item);
    }

       将每一个弹幕项添加到视图上,并给View添加一个TranslateAnimation动画,当动画结束时,将View从视图上移除。


  1. private void showBarrageItem(final BarrageItem item) {  
  2.   
  3.         int leftMargin = this.getWidth();  
  4.   
  5.         LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
  6.         params.addRule(RelativeLayout.ALIGN_PARENT_TOP);  
  7.         params.topMargin = item.verticalPos;  
  8.         this.addView(item.textView, params);  
  9.         Animation anim = generateTranslateAnim(item, leftMargin);  
  10.         anim.setAnimationListener(new Animation.AnimationListener() {  
  11.             @Override  
  12.             public void onAnimationStart(Animation animation) {  
  13.   
  14.             }  
  15.   
  16.             @Override  
  17.             public void onAnimationEnd(Animation animation) {  
  18.                 item.textView.clearAnimation();  
  19.                 BarrageView.this.removeView(item.textView);  
  20.             }  
  21.   
  22.             @Override  
  23.             public void onAnimationRepeat(Animation animation) {  
  24.   
  25.             }  
  26.         });  
  27.         item.textView.startAnimation(anim);  
  28.     }  
  29.   
  30.     private TranslateAnimation generateTranslateAnim(BarrageItem item, int leftMargin) {  
  31.         TranslateAnimation anim = new TranslateAnimation(leftMargin, -item.textMeasuredWidth, 00);  
  32.         anim.setDuration(item.moveSpeed);  
  33.         anim.setInterpolator(new AccelerateDecelerateInterpolator());  
  34.         anim.setFillAfter(true);  
  35.         return anim;  
  36.     }  
private void showBarrageItem(final BarrageItem item) {

        int leftMargin = this.getWidth();

        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        params.topMargin = item.verticalPos;
        this.addView(item.textView, params);
        Animation anim = generateTranslateAnim(item, leftMargin);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                item.textView.clearAnimation();
                BarrageView.this.removeView(item.textView);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        item.textView.startAnimation(anim);
    }

    private TranslateAnimation generateTranslateAnim(BarrageItem item, int leftMargin) {
        TranslateAnimation anim = new TranslateAnimation(leftMargin, -item.textMeasuredWidth, 0, 0);
        anim.setDuration(item.moveSpeed);
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        anim.setFillAfter(true);
        return anim;
    }
       这样就完成了弹幕的功能,实现原理并不复杂。可以根据具体的需求来增加更多的控制,如控制每一行弹幕不重复,控制弹幕移动的Interpolator产生不同的滑动效果等等。


源码下载 


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值