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

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

最新文章

  1. Freemarker与Springmvc
  2. jQuery入门(2)使用jQuery操作元素的属性与样式
  3. eclipse 快捷键
  4. 【PHP面向对象(OOP)编程入门教程】19.抽象方法和抽象类(abstract)
  5. C# 对象实例几种方法
  6. AspNetPager学习使用1
  7. UVaLive 7269 Snake Carpet (找规律,模拟)
  8. 学习Python前序
  9. Linq101-Aggregate
  10. java 判断浏览器
  11. commons-logging log4j的联系区别
  12. hdu_5620_KK&#39;s Steel(水题)
  13. xampp使用中mysql端口被占用问题的解决方案
  14. BZOJ 3569: DZY Loves Chinese II [高斯消元XOR 神题]
  15. solr的认识、linux下安装、java下使用(含下载资源)
  16. 输入两个整数n和m,从数列1,2,3,……n中随意取几个数,使其和等于m
  17. HashSet TreeSet
  18. MySQL -- 全文检索(查询扩展检索)
  19. php 关于文件的一些封装好的函数
  20. QT源码之Qt信号槽机制与事件机制的联系

热门文章

  1. 常见的问题:https://localhost:1158/em 无法打开
  2. Selenium中验证码处理
  3. P1664 每日打卡心情好
  4. nodejs+multiparty 文件上传
  5. JS进阶-特殊形式的函数-内部私有函数
  6. ASP.NET MVC IIS7 403.14-Forbidden
  7. IOS存储目录documents你在哪里啊
  8. 修改JRE system library
  9. Long time no blogging
  10. sybase sql anywhere 5.0 安装后sybase central中无法打开视图等的解决办法