Android弹幕编程设计实现的解决方案(一)

简介: Android弹幕编程设计实现的解决方案(一)在现在的一些视频类网站、视频类直播网站,比如A站和B站,当视频在播放的时候,会在屏幕上出现一些滚动的字幕,这些字幕是UGC,通常是用户的评论,称之为“弹幕”,这些弹幕一般从右往左滚动,以符合人类的阅读习惯。


Android弹幕编程设计实现的解决方案(一)

在现在的一些视频类网站、视频类直播网站,比如A站和B站,当视频在播放的时候,会在屏幕上出现一些滚动的字幕,这些字幕是UGC,通常是用户的评论,称之为“弹幕”,这些弹幕一般从右往左滚动,以符合人类的阅读习惯。
现在给出一个实现Android平台上的弹幕编程设计实现方案。
(1)要注意的是,一般视频播放是一个view,比如是VideoView,弹幕是在VideoView上面滚动,这就要求弹幕必须和VideoView完全密合在一起,至少在视觉上让用户看上去觉得这就是直接在视频画面上写上去的。那么在下面的这个例子中,就干脆直接继承自一个相对布局RelativeLayout。因为是一个布局文件,如果使用VideoView这类的播放器,就好办了,直接设置view的layout宽和高均为match_parent即可。
(2)弹幕一般是随机批量显示。我观察了一些热门网站的弹幕显示,它们是随机的,我在处理弹幕字幕文本时候,设计了一个set方法,一次性批量喂给弹幕一个数据池子(实际上就是在弹幕类里面的一个LinkedList数据队列texts),让弹幕从这些池子中每次随机抽出一个显示。假设上层应用的文本有更新(比如用户有新的评论添加进来),直接追加到队列头部。

以下是全部源代码实现。
核心关键的弹幕相对布局BarrageRelativeLayout.java:

package zhangphil.demo;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.LinkedList;
import java.util.Random;

public class BarrageRelativeLayout extends RelativeLayout {

    private Context mContext;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(msg.what==RANDOM_SHOW) {
                String text = texts.get(random.nextInt(texts.size()));
                BarrageTextItem item = new BarrageTextItem(text);
                showBarrageItem(item);

                //每个弹幕产生的间隔时间随机
                int duration = (int) ((BARRAGE_GAP_MAX_DURATION - BARRAGE_GAP_MIN_DURATION) * Math.random());
                this.sendEmptyMessageDelayed(RANDOM_SHOW, duration);
            }


        }
    };

    public static int RANDOM_SHOW=0x0a1;
    public static int SEQ_SHOW=0x0a2;

    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 LinkedList<String> texts = null;

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

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

    public BarrageRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

        init();
    }

    private void init() {
        texts = new LinkedList<String>();
    }

    public void show(int type){
        int duration = (int) ((BARRAGE_GAP_MAX_DURATION - BARRAGE_GAP_MIN_DURATION) * Math.random());
        mHandler.sendEmptyMessageDelayed(type, duration);
    }

    //显示一批弹幕文本
    //相当于给弹幕设置数据源
    public void setBarrageTexts(LinkedList<String> texts) {
        this.texts = texts;
    }

    //头部第一个位置追加,最新的。
    public void addBarrageText(String text) {
        this.texts.add(0,text);
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        totalHeight = getMeasuredHeight();
        lineHeight = getLineHeight();
        totalLine = totalHeight / lineHeight;
    }

    private void showBarrageItem(final BarrageTextItem item) {
        int leftMargin = this.getRight() - this.getLeft() - this.getPaddingLeft();
        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();
                BarrageRelativeLayout.this.removeView(item.textView);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

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

    private TranslateAnimation generateTranslateAnim(BarrageTextItem 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;
    }

    /**
     * 计算TextView中字符串的长度
     *
     * @param text 要计算的字符串
     * @param Size 字体大小
     * @return TextView中字符串的长度
     */
    public float getTextWidth(BarrageTextItem item, String text, float Size) {
        Rect bounds = new Rect();
        TextPaint paint;
        paint = item.textView.getPaint();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return bounds.width();
    }

    /**
     * 获得每一行弹幕的最大高度
     *
     * @return
     */
    private int getLineHeight() {
        BarrageTextItem item = new BarrageTextItem();

        //传递进去一个非空字符串,目的是为了获得一个计算值
        String tx = "no null data";

        item.textView = new TextView(mContext);
        item.textView.setText(tx);
        item.textView.setTextSize(maxSize);

        Rect bounds = new Rect();
        TextPaint paint;
        paint = item.textView.getPaint();
        paint.getTextBounds(tx, 0, tx.length(), bounds);
        return bounds.height();
    }

    //弹幕的一个文本item
    public class BarrageTextItem {
        public TextView textView;
        public int textColor;
        public String text;
        public int textSize;
        public int moveSpeed;//移动速度
        public int verticalPos;//垂直方向显示的位置
        public int textMeasuredWidth;//字体显示占据的宽度

        public BarrageTextItem() {

        }

        public BarrageTextItem(String text) {
            this.textSize = (int) (minSize + (maxSize - minSize) * Math.random());
            this.text = text;
            this.textColor = Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            this.textView = new TextView(mContext);
            textView.setText(text);
            textView.setTextSize(textSize);
            textView.setTextColor(textColor);
            textMeasuredWidth = (int) getTextWidth(this, text, textSize);
            moveSpeed = (int) (minSpeed + (maxSpeed - minSpeed) * Math.random());
            if (totalLine == 0) {
                totalHeight = getMeasuredHeight();
                lineHeight = getLineHeight();
                totalLine = totalHeight / lineHeight;
            }
            verticalPos = random.nextInt(totalLine) * lineHeight;
        }
    }
}


直接写进布局当作一个一般的相对布局使用:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="zhangphil.demo.MainActivity">

    <zhangphil.demo.BarrageRelativeLayout
        android:id="@+id/barrageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white" />

</RelativeLayout>


上层activity使用方法:

package zhangphil.demo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.LinkedList;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BarrageRelativeLayout mBarrageRelativeLayout = (BarrageRelativeLayout) findViewById(R.id.barrageView);

        String[] itemText = {"zhangphil@csdn 0", "zhangphil 1", "zhang phil 2","zhang 3","phil 4","zhangphil ... 5", "***zhangphil 6", "zhang phil csdn 7", "zhang ... phil 8", "phil... 9", "http://blog.csdn.net/zhangphil 10"};
        LinkedList<String> texts=new LinkedList<String>();
        for(int i=0;i<itemText.length;i++){
            texts.add(itemText[i]);
        }
        mBarrageRelativeLayout.setBarrageTexts(texts);

        mBarrageRelativeLayout.show(BarrageRelativeLayout.RANDOM_SHOW);
    }
}


代码运行结果(弹幕从右往左滚动显示):



相关文章
|
21天前
|
安全 Shell Android开发
Android系统 init.rc sys/class系统节点写不进解决方案和原理分析
Android系统 init.rc sys/class系统节点写不进解决方案和原理分析
34 0
|
1月前
|
XML Android开发 数据格式
android点击FrameLayout、LinearLayout等父布局没响应的原因以及解决方案
android点击FrameLayout、LinearLayout等父布局没响应的原因以及解决方案
34 2
|
2月前
|
Ubuntu 网络协议 Java
【Android平板编程】远程Ubuntu服务器code-server编程写代码
【Android平板编程】远程Ubuntu服务器code-server编程写代码
|
6天前
|
Ubuntu Android开发 数据安全/隐私保护
【Android平板编程】远程Ubuntu服务器Code-Server编程写代码
【Android平板编程】远程Ubuntu服务器Code-Server编程写代码
|
8天前
|
Android开发
Android中Glide加载Https图片失败的解决方案
Android中Glide加载Https图片失败的解决方案
16 1
|
21天前
|
安全 编译器 API
Android HAL深入探索(5): 调试HAL报错与解决方案
Android HAL深入探索(5): 调试HAL报错与解决方案
27 1
|
21天前
|
存储 应用服务中间件 网络安全
Android 网络链接稳定性测试解决方案
Android 网络链接稳定性测试解决方案
21 0
|
1月前
|
编译器 调度 Android开发
构建高效Android应用:Kotlin协程的优雅解决方案
【4月更文挑战第14天】 在移动开发领域,性能优化和资源管理是提升用户体验的关键因素。随着Kotlin语言在Android平台上的普及,协程作为其核心特性之一,为开发者提供了一种轻量级的并发处理手段。本文将深入探讨Kotlin协程在Android应用中的运用,通过实例分析其如何简化异步任务,提升应用响应性,并保证代码的简洁与可维护性。我们将透过源码剖析、性能对比及最佳实践,揭示协程在现代Android开发中的重要角色。
|
2月前
|
JSON Android开发 数据格式
android 使用GSON 序列化对象出现字段被优化问题解决方案
android 使用GSON 序列化对象出现字段被优化问题解决方案
|
2月前
|
Ubuntu 网络协议 Java
在Android平板上使用code-server公网远程Ubuntu服务器编程
在Android平板上使用code-server公网远程Ubuntu服务器编程