Android 教你亲手打造酷炫的弹幕效果

转自:http://blog.csdn.net/qq_22770457/article/details/52059912


公司的新产品上线需要添加的弹幕功能,于是花了一天时间写了一个Demo。

效果实现如下:

一开始的思路是:

1、首先实现一个自定义的Layout,在其中获得需要展示的弹幕数组,每个弹幕数组的项包括弹幕文本以及图片Url地址。

2、在Layout内部使用Handler或者计时线程循环发送弹幕。

3、弹幕实现采用自定义弹幕View,配合动画实现滚屏呈现。

总结之后发现主要的难点还是在弹幕的出现位置选择以及弹幕如何确保及时销毁上(我会说一开始调试的时候出现满屏弹幕的华丽场景么。。),以及如何实现组件的复用,并尽可能提高性能。还要注意一些需要实现的功能点:通过Url获得图片(可通过图片缓存加载框架实现并替代)、防止弹幕堆叠(这个算法实现还是比较容易的)。

之后发现再写个自定义的弹幕view(左边一个圆形头像右边文字,外框椭圆背景透明)有点麻烦,于是采用了ListView里item复用的思想,使用了一个Item布局轻松实现辣~

好在最近一直在写公司新项目的界面,各种技巧运用得比较熟练,弹幕Demo的编写全程没有碰到什么压力,倒是最后忘记加网络权限导致调试了半天。。。(哭泣)。

实现步骤:

1、实现主布局:

弹幕区域的位置是可以自己调整的,理论上来说可以安置在屏幕任一位置上。

barrageview_test.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:orientation="vertical"  
  4.               android:layout_width="match_parent"  
  5.               android:layout_height="match_parent">  
  6.   
  7.     <com.whale.nangua.toquan.view.BarrageView  
  8.         android:id="@+id/barrageview"  
  9.         android:background="@drawable/testbackground"  
  10.         android:layout_centerHorizontal="true"  
  11.         android:layout_centerVertical="true"  
  12.         android:layout_width="match_parent"  
  13.         android:layout_height="200dp"/>  
  14. </RelativeLayout>  

2、实现弹幕item布局:

使用了自定义的圆圈类实现了圆形头像的效果,网上一搜一大堆或者评论留言这里就不填源码占篇幅了。

barrageview_item.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:orientation="horizontal"  
  4.               android:background="@drawable/barrage_shape"  
  5.               android:layout_width="wrap_content"  
  6.               android:layout_height="50dp">  
  7.   
  8.     <com.whale.nangua.toquan.view.NGNormalCircleImageView  
  9.         android:src="@drawable/pumpkin"  
  10.         android:id="@+id/barrageview_item_img"  
  11.         android:layout_width="50dp"  
  12.         android:layout_height="match_parent"/>  
  13.   
  14.     <TextView  
  15.         android:maxEms="10"  
  16.         android:textColor="@android:color/white"  
  17.         android:layout_marginLeft="10dp"  
  18.         android:layout_marginRight="10dp"  
  19.         android:gravity="center"  
  20.         android:text="测试弹幕"  
  21.         android:singleLine="true"  
  22.         android:id="@+id/barrageview_item_tv"  
  23.         android:layout_width="wrap_content"  
  24.         android:layout_height="match_parent"/>  
  25. </LinearLayout>  
3、实现测试用的Activity
  1. package com.whale.nangua.toquan;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.util.Log;  
  6.   
  7. import com.whale.nangua.toquan.bean.Barrage;  
  8. import com.whale.nangua.toquan.view.BarrageView;  
  9.   
  10. import java.util.ArrayList;  
  11.   
  12. /** 
  13.  * Created by nangua on 2016/7/18. 
  14.  */  
  15. public class TestAty extends Activity {  
  16.     BarrageView barrageview;  
  17.     ArrayList<Barrage> date;  
  18.   
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.barrageview_test);  
  23.         initView();  
  24.     }  
  25.   
  26.     private void initView() {  
  27.         date = new ArrayList<>();  
  28.         for (int i = 0; i < 100; i++) {  
  29.             date.add(new Barrage(  
  30.                     "测试弹幕" + i, "http://pic.818today.com/imgsy/image/2016/0215/6359114592207963687677523.jpg"));  
  31.         }  
  32.   
  33.         barrageview = (BarrageView) findViewById(R.id.barrageview);  
  34.         Log.d("xiaojingyu", date.size() + "");  
  35.         barrageview.setSentenceList(date);  
  36.     }  
  37. }  

4、弹幕类BarrageView.java
  1. package com.whale.nangua.toquan.view;  
  2.   
  3. import android.animation.Animator;  
  4. import android.animation.ObjectAnimator;  
  5. import android.content.Context;  
  6. import android.graphics.Bitmap;  
  7. import android.graphics.BitmapFactory;  
  8. import android.graphics.Canvas;  
  9. import android.os.Bundle;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.util.AttributeSet;  
  13. import android.util.Log;  
  14. import android.view.LayoutInflater;  
  15. import android.widget.FrameLayout;  
  16. import android.widget.LinearLayout;  
  17. import android.widget.TextView;  
  18.   
  19. import com.whale.nangua.toquan.R;  
  20. import com.whale.nangua.toquan.bean.Barrage;  
  21.   
  22. import java.io.InputStream;  
  23. import java.net.HttpURLConnection;  
  24. import java.net.URL;  
  25. import java.util.ArrayList;  
  26.   
  27. /** 
  28.  * 2秒一条 
  29.  * 屏幕上同时存在5条 
  30.  * Created by nangua on 2016/7/28. 
  31.  */  
  32. public class BarrageView extends FrameLayout {  
  33.     private static ArrayList<Barrage> date = new ArrayList<>(); //数据  
  34.     private int nowIndex = 0//date的下标  
  35.     private Bitmap nowBitmap; //当前图片  
  36.     int width;    //控件宽  
  37.     int height;  //控件高  
  38.     float scale;    //像素密度  
  39.     FrameLayout frameLayout;  
  40.     FrameLayout.LayoutParams tvParams;  
  41.   
  42.     static boolean IS_START = false;    //判断是否开始  
  43.   
  44.     long alltime; //视频总时长  
  45.     long starttime; //开始时间  
  46.   
  47.     //    LinearLayout layout;  
  48.   
  49.     Handler handler = new Handler() {  
  50.         @Override  
  51.         public void handleMessage(Message msg) {  
  52.             Barrage barrage = (Barrage) msg.getData().getSerializable("barrage");  
  53.             final LinearLayout layout = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.barrageview_item, null);  
  54.             layout.setLayoutParams(tvParams);  
  55.             //随机获得Y值  
  56.             layout.setY(getRamdomY());  
  57.             layout.setX(width + layout.getWidth());  
  58.   
  59.             //设置文字  
  60.             TextView textView = (TextView) layout.findViewById(R.id.barrageview_item_tv);  
  61.             textView.setText(barrage.getBarrageInfo());  
  62.   
  63.             //设置图片  
  64.             NGNormalCircleImageView ngNormalCircleImageView = (NGNormalCircleImageView) layout.findViewById(R.id.barrageview_item_img);  
  65.             if (nowBitmap != null) {  
  66.   
  67.                 ngNormalCircleImageView.setImageBitmap(nowBitmap);  
  68.             }  
  69.   
  70.             frameLayout.addView(layout);  
  71.   
  72.             final ObjectAnimator anim = ObjectAnimator.ofFloat(layout, "translationX", -width);  
  73.             anim.setDuration(10000);  
  74.   
  75.             //释放资源  
  76.             anim.addListener(new Animator.AnimatorListener() {  
  77.                 @Override  
  78.                 public void onAnimationStart(Animator animation) {  
  79.                 }  
  80.                 @Override  
  81.                 public void onAnimationEnd(Animator animation) {  
  82.                     anim.cancel();  
  83.                     layout.clearAnimation();  
  84.                     frameLayout.removeView(layout);  
  85.                 }  
  86.   
  87.                 @Override  
  88.                 public void onAnimationCancel(Animator animation) {  
  89.                 }  
  90.   
  91.                 @Override  
  92.                 public void onAnimationRepeat(Animator animation) {  
  93.   
  94.                 }  
  95.             });  
  96.             anim.start();  
  97.         }  
  98.     };  
  99.   
  100.     /** 
  101.      * 使用httprulconnection通过发送网络请求path获得bitmap 
  102.      * @param path 
  103.      * @return 
  104.      */  
  105.     public static Bitmap getBitmapFromUrl(String path) {  
  106.         try {  
  107.             //获得url  
  108.             URL url = new URL(path);  
  109.             //打开httprulconnection获得实例  
  110.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  111.             //设置超时时间  
  112.             conn.setConnectTimeout(5000);  
  113.             //设置Get  
  114.             conn.setRequestMethod("GET");  
  115.             //连接成功  
  116.             if (conn.getResponseCode() == 200) {  
  117.                 //获得输入流  
  118.                 InputStream inputStream = conn.getInputStream();  
  119.                 //得到bitmap  
  120.                 Bitmap bitmap = BitmapFactory.decodeStream(inputStream);  
  121.                 if (bitmap == null) {  
  122.                 }  
  123.                 //返回  
  124.                 return bitmap;  
  125.             }  
  126.             //错误信息处理  
  127.         } catch (Exception e) {  
  128.             //打印错误信息  
  129.             e.printStackTrace();  
  130.         }  
  131.         return null;  
  132.     }  
  133.   
  134.     int lastY;//上一次出现的Y值  
  135.     /** 
  136.      * 获得随机的Y轴的值 
  137.      * 
  138.      * @return 
  139.      */  
  140.     private float getRamdomY() {  
  141.         int tempY;  
  142.         int rY;  
  143.         int result = 0;  
  144.         // height * 2 / 4 - 25  
  145.         //首先随机选择一条道路  
  146.         int nowY = (int) (Math.random() * 3);  
  147.         switch (nowY) {  
  148.             case 0:  
  149.                 nowY = avoidTheSameY(nowY,lastY);  
  150.                 //第一条  
  151.                 tempY = height / 4 - 25;  
  152.                 rY = (int) (Math.random() * height / 4);  
  153.                 if (rY >= height / 8) {  
  154.                     result = tempY + rY;  
  155.                 } else {  
  156.                     result = tempY - rY + 50 ;  
  157.                 }  
  158.                 lastY = nowY;  
  159.                 break;  
  160.             case 1:  
  161.                 nowY = avoidTheSameY(nowY,lastY);  
  162.                 //第二条  
  163.                 tempY = height / 2 - 25;  
  164.                 rY = (int) (Math.random() * height / 4);  
  165.                 if (rY >= height / 8) {  
  166.                     result = tempY + rY;  
  167.                 } else {  
  168.                     result = tempY - rY;  
  169.                 }  
  170.                 lastY = nowY;  
  171.                 break;  
  172.             case 2:  
  173.                 nowY = avoidTheSameY(nowY,lastY);  
  174.                 //第三条  
  175.                 tempY = height * 3 / 4 - 25;  
  176.                 rY = (int) (Math.random() * height / 4);  
  177.                 if (rY >= height / 8) {  
  178.                     result = tempY + rY -50;  
  179.                 } else {  
  180.                     result = tempY - rY;  
  181.                 }  
  182.                 lastY = nowY;  
  183.                 break;  
  184.         }  
  185.         return result;  
  186.     }  
  187.   
  188.     /** 
  189.      * 避免Y重合的方法 
  190.      * @param lastY 
  191.      * @return 
  192.      */  
  193.     private int avoidTheSameY(int nowY,int lastY) {  
  194.         if (nowY == lastY) {  
  195.             nowY ++;  
  196.         }  
  197.         if (nowY == 4) {  
  198.             nowY = 0;  
  199.         }  
  200.         return nowY;  
  201.     }  
  202.   
  203.   
  204.     public BarrageView(Context context, AttributeSet attrs) {  
  205.         super(context, attrs);  
  206.   
  207.     }  
  208.   
  209.     @Override  
  210.     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
  211.         super.onLayout(changed, left, top, right, bottom);  
  212.         width = getWidth(); //宽度  
  213.         height = getHeight();   //高度  
  214.         init();  
  215.     }  
  216.   
  217.     private void init() {  
  218.         setTime(600000);    //设置初始时长,改完记得删  
  219.   
  220.         starttime = System.currentTimeMillis();  
  221.   
  222.         scale = this.getResources().getDisplayMetrics().density;  
  223.         //获得自身实例  
  224.         frameLayout = (FrameLayout) findViewById(R.id.barrageview);  
  225.         tvParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, 50);  
  226.   
  227.         if (IS_START) {  
  228.             //开始动画线程  
  229.             startBarrageView();  
  230.             IS_START = false;  
  231.         }  
  232.     }  
  233.   
  234.     public void startBarrageView() {  
  235.         //开启线程发送弹幕  
  236.         new Thread() {  
  237.             @Override  
  238.             public void run() {  
  239.   
  240.                 while ((System.currentTimeMillis() - starttime < alltime)  
  241.                         && (nowIndex <= date.size() - 1)  
  242.                         ){  
  243.   
  244.                     try {  
  245.                         nowBitmap = getBitmapFromUrl(date.get(nowIndex).getBarrageUrl());  
  246.                         Message message = new Message();  
  247.                         Bundle bundle = new Bundle();  
  248.                         bundle.putSerializable("barrage",date.get(nowIndex));  
  249.                         nowIndex ++;  
  250.                         message.setData(bundle);  
  251.                         handler.sendMessage(message);  
  252.                         Thread.sleep((long) (Math.random() * 3000) + 1000);  
  253.                     } catch (InterruptedException e) {  
  254.                         e.printStackTrace();  
  255.                     }  
  256.                 }  
  257.                 return;  
  258.             }  
  259.         }.start();  
  260.     }  
  261.   
  262.   
  263.     @Override  
  264.     protected void onDraw(Canvas canvas) {  
  265.         super.onDraw(canvas);  
  266.     }  
  267.   
  268.     //设置数据  
  269.     public void setSentenceList(ArrayList<Barrage> date1) {  
  270.         date = date1;  
  271.         IS_START = true;  
  272.     }  
  273.   
  274.     //获得视频总时长  
  275.     public void setTime(long time) {  
  276.         alltime = time;  
  277.     }  
  278.   
  279. }  
实现的思路大概跟开头的描述是一样的,但是这还只是一个比较简陋的雏形,有大量可模块化的功能点进行扩充,

比如可设置的视频时长,弹幕速率,弹幕字体颜色,弹幕排列方式等等等等都可以自己定制,


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值