Android直播中彈幕效果實現
阿新 • • 發佈:2019-01-29
在B站或者其他視訊網站看視訊時,常常會開啟彈幕效果,邊看節目邊看大家的吐槽。彈幕看起來很有意思,今天我們就來實現一個簡單的彈幕效果。
從直觀上,彈幕效果就是在一個ViewGroup上增加一些View,然後讓這些View移動起來。所以,整體的實現思路大概是這樣的:
1、定義一個RelativeLayout,在裡面動態新增TextView。
2、這些TextView的字型大小、顏色、移動速度、初始位置都是隨機的。
3、將TextView新增到RelativeLayout的右邊緣,每隔一段時間新增一個。
4、對每個TextView做平移動畫,使得TextView從右向左移動。
5、當TextView從左邊移動出螢幕,將TextView從RelativeLayout中移除。
有了思路下面就來看具體的程式碼。
首先定義BarrageItem,用來儲存每一個彈幕項的相關資訊,包括字型內容、字型大小顏色、移動速度、垂直方向的位置、字型佔據的寬度等。
[java] view plain copy print?- publicclass BarrageItem {
- public TextView textView;
- publicint textColor;
- public String text;
- publicint textSize;
- publicint moveSpeed;//移動速度
- publicint verticalPos;//垂直方向顯示的位置
- publicint textMeasuredWidth;//字型顯示佔據的寬度
- }
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,由於彈幕的字型顏色大小和移動速度都是隨機的,需要定義最大最小值來限定它們的範圍,然後通過產生隨機數來設定它們在這個範圍內的值。另外還需要定義彈幕的文字內容,這裡是直接寫死的一些固定值。
[java] view plain copy print?- private Context mContext;
- private BarrageHandler mHandler = new BarrageHandler();
- private Random random = new Random(System.currentTimeMillis());
- privatestaticfinallong BARRAGE_GAP_MIN_DURATION = 1000;//兩個彈幕的最小間隔時間
- privatestaticfinallong BARRAGE_GAP_MAX_DURATION = 2000;//兩個彈幕的最大間隔時間
- privateint maxSpeed = 10000;//速度,ms
- privateint minSpeed = 5000;//速度,ms
- privateint maxSize = 30;//文字大小,dp
- privateint minSize = 15;//文字大小,dp
- privateint totalHeight = 0;
- privateint lineHeight = 0;//每一行彈幕的高度
- privateint totalLine = 0;//彈幕的行數
- private String[] itemText = {“是否需要幫忙”, “what are you 弄啥來”, “哈哈哈哈哈哈哈”, “搶佔沙發。。。。。。”, “************”, “是否需要幫忙”,“我不會輕易的狗帶”, “嘿嘿”, “這是我見過的最長長長長長長長長長長長的評論”};
- privateint 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();
- }
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()得到的高度不為空。 [java] view plain copy print?
- @Override
- publicvoid onWindowFocusChanged(boolean hasWindowFocus) {
- super.onWindowFocusChanged(hasWindowFocus);
- totalHeight = getMeasuredHeight();
- lineHeight = getLineHeight();
- totalLine = totalHeight / lineHeight;
- }
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
totalHeight = getMeasuredHeight();
lineHeight = getLineHeight();
totalLine = totalHeight / lineHeight;
}
通過Handler的sendEmptyMessageDelayed每隔隨機的時間產生一個彈幕項。下面的程式碼設定彈幕項的屬性。
[java] view plain copy print?- class BarrageHandler extends Handler {
- @Override
- publicvoid handleMessage(Message msg) {
- super.handleMessage(msg);
- generateItem();
- //每個彈幕產生的間隔時間隨機
- int duration = (int) ((BARRAGE_GAP_MAX_DURATION - BARRAGE_GAP_MIN_DURATION) * Math.random());
- this.sendEmptyMessageDelayed(0, duration);
- }
- }
- privatevoid 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);
- }
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從檢視上移除。 [java] view plain copy print?
- privatevoid 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
- publicvoid onAnimationStart(Animation animation) {
- }
- @Override
- publicvoid onAnimationEnd(Animation animation) {
- item.textView.clearAnimation();
- BarrageView.this.removeView(item.textView);
- }
- @Override
- publicvoid 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;
- }
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產生不同的滑動效果等等。