Android Bullet Screen realization: Based on the B-Station bullet screen Open source system (1)

Source: Internet
Author: User

??

Android Bullet Screen realization: Based on the B-Station bullet screen Open source system (1)

Today's video playback, popular in the video bubble screen. This is done relatively mature, stable, use a lot of bomb screen system, when the push B station of the barrage system, B station's barrage system has been as open source project on GitHub, its project address: Https://github.com/Bilibili/DanmakuFlameMaster
Based on the B-station open-source Bullet screen project, a simple example is given to deliver a simple text barrage.
The first step is to introduce the B-station project to the Android Build.gradle file:

repositories {    Jcenter ()}dependencies {compile ' com.github.ctiao:danmakuflamemaster:0.7.3 ' compile ' com.github.ctiao:ndkbitmap-armv7a:0.7.3 '}


The second step is to write a layout file that introduces the B station's barrage view:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical "&    Gt <button android:id= "@+id/show" android:layout_width= "wrap_content" android:layout_height= "Wrap_con Tent "android:text=" shows the barrage "/> <button android:id=" @+id/hide "android:layout_width=" Wrap_conte NT "android:layout_height=" Wrap_content "android:text=" hidden barrage "/> <button android:id=" @+id/sen  Dtext "android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:text=" Send text bullet screen " /> <button android:id= "@+id/pause" android:layout_width= "Wrap_content" Android:layout_heigh t= "Wrap_content" android:text= "pause the barrage"/> <button android:id= "@+id/resume" Android:layout_widt H= "Wrap_content" Androidoid:layout_height= "Wrap_content" android:text= "Restart the barrage"/> <master.flame.danmaku.ui.widget.danmakuview Android:id= "@+id/danmakuview" android:layout_width= "match_parent" android:layout_height= "Match_parent"/&gt ;</linearlayout>


The third step is to write the upper Java code (the Java code is modified from the demo code on GitHub on the B-Station bullet screen):

Package Zhangphil.danmaku;import Android.app.activity;import Android.graphics.color;import android.os.Bundle; Import Android.util.log;import android.view.view;import Android.widget.button;import Java.util.HashMap;import Master.flame.danmaku.danmaku.model.basedanmaku;import Master.flame.danmaku.danmaku.model.danmakutimer;import Master.flame.danmaku.danmaku.model.idisplayer;import Master.flame.danmaku.danmaku.model.android.DanmakuContext; Import Master.flame.danmaku.ui.widget.danmakuview;public class Mainactivity extends Activity {private Danmakuview Mdan    Makuview;    Private Danmakucontext Mcontext;    Private Acfundanmakuparser Mparser;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mdanmakuview = (Danmakuview) Findviewbyid (R.id.danmakuview);        Button show = (Button) Findviewbyid (r.id.show);        Button hide = (Button) Findviewbyid (r.id.hide); Button SenDtext = (Button) Findviewbyid (R.id.sendtext);        Button pause = (Button) Findviewbyid (R.id.pause);        Button resume = (Button) Findviewbyid (R.id.resume);                Show.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Mdanmakuview.show ();        }        });                Hide.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Mdanmakuview.hide ();        }        });                Sendtext.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Send a pop-up screen sendtextmessage () Every time you click on the button;        }        });                Pause.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {            Mdanmakuview.pause ();        }        }); Resume.setonclicklistener (New View.onclicklistener () {@OVerride public void OnClick (View v) {mdanmakuview.resume ();        }        });    Init ();        } private void Init () {mcontext = Danmakucontext.create ();        Sets the maximum number of lines to display Hashmap<integer, integer> maxlinespair = new hashmap<> (); Maxlinespair.put (BASEDANMAKU.TYPE_SCROLL_RL, 8);        Maximum display of the rolling barrage 5 lines//Set whether to prohibit overlapping hashmap<integer, boolean> Overlappingenablepair = new hashmap<> ();        Overlappingenablepair.put (BASEDANMAKU.TYPE_SCROLL_RL, true);        Overlappingenablepair.put (Basedanmaku.type_fix_top, true);                Mcontext.setdanmakustyle (Idisplayer.danmaku_style_stroken, 10)//stroke thickness. setduplicatemergingenabled (false) . Setscrollspeedfactor (1.2f)//The speed of the barrage. Attention! The smaller the value, the faster it gets! The higher the value, the slower the speed. by Phil Setscaletextsize (1.2f)//Scaled value//.setcachestuffer (new Spannedcachestuffer (), MCa Chestufferadapter)//graphic mix use spannedcachestuffer//. Setcachestuffer(New Backgroundcachestuffer ())//Draw background using Backgroundcachestuffer. Setmaximumlines (Maxlinespair)        . preventoverlapping (Overlappingenablepair);        Mparser = new Acfundanmakuparser ();        Mdanmakuview.prepare (Mparser, Mcontext);        Mdanmakuview.showfps (TRUE);        Mdanmakuview.enabledanmakudrawingcache (TRUE);  if (Mdanmakuview! = null) {Mdanmakuview.setcallback (New Master.flame.danmaku.controller.DrawHandler.Callback () {@Override public void Updatetimer (Danmakutimer timer) {} @ Override public void drawingfinished () {} @Override public Vo                ID Danmakushown (Basedanmaku danmaku) {log.d ("Bullet screen text", "Danmakushown text=" + danmaku.text);                } @Override public void prepared () {Mdanmakuview.start ();        }            });    }private void Sendtextmessage () {Adddanmaku (true); } private void Adddanmaku (Boolean islive) {Basedanmaku Danmaku = MContext.mDanmakuFactory.createDanmaku (Basedan Maku.        TYPE_SCROLL_RL);        if (Danmaku = = NULL | | mdanmakuview = = NULL) {return;        } danmaku.text = "Zhangphil @ csdn:" + system.currenttimemillis ();        danmaku.padding = 5;  danmaku.priority = 0;        May be filtered by various filters and hidden display danmaku.islive = islive;        Danmaku.settime (Mdanmakuview.getcurrenttime () + 1200); Danmaku.textsize = 20f * (Mparser.getdisplayer (). Getdensity ()-0.6f); Text bullet screen font size Danmaku.textcolor = Getrandomcolor (); The color of the text Danmaku.textshadowcolor = Getrandomcolor (); Text Bullet screen stroke color//danmaku.underlinecolor = Color.dkgray; Text bullet screen underline color danmaku.bordercolor = Getrandomcolor ();    The color of the Border Mdanmakuview.adddanmaku (Danmaku);        } @Override protected void OnPause () {super.onpause (); if (Mdanmakuview! = Null && mdanmakuview.isprepared ()) {mdanmakuview.pause ();        }} @Override protected void Onresume () {super.onresume (); if (Mdanmakuview! = null && mdanmakuview.isprepared () && mdanmakuview.ispaused ()) {Mdanmakuvie        W.resume ();        }} @Override protected void OnDestroy () {Super.ondestroy ();            if (Mdanmakuview! = null) {//dont forget release!            Mdanmakuview.release ();        Mdanmakuview = null; }}/** * Randomly select a color from a range of colors * * @return */private int getrandomcolor () {int[] colors = {Co Lor.        RED, Color.yellow, Color.Blue, Color.green, Color.cyan, Color.Black, Color.dkgray};        int i = ((int) (Math.random () *))% Colors.length;    return colors[i]; }}


Code Run Results



It is important to note that this example uses a barrage called Acfundanmakuparser parser, which has to be written by itself and implemented in JSON data format. This kind of writing good basic can be used to stabilize the use, now give Acfundanmakuparser all the source code:

Package Zhangphil.danmaku;import Org.json.jsonarray;import Org.json.jsonexception;import org.json.JSONObject; Import Master.flame.danmaku.danmaku.model.basedanmaku;import Master.flame.danmaku.danmaku.model.android.Danmakus ; Import Master.flame.danmaku.danmaku.parser.basedanmakuparser;import Master.flame.danmaku.danmaku.parser.android.jsonsource;import master.flame.danmaku.danmaku.util.danmakuutils;/* * * Created by Phil on 2017/3/29. */public class Acfundanmakuparser extends Basedanmakuparser {public acfundanmakuparser () {} public danmakus par Se () {if (This.mdatasource! = null && this.mdatasource instanceof jsonsource) {Jsonsource JSON            Source = (jsonsource) This.mdatasource;        Return This.doparse (Jsonsource.data ());        } else {return new Danmakus ();        }} private Danmakus Doparse (Jsonarray danmakulistdata) {Danmakus Danmakus = new Danmakus (); if (danmakulistdata! = null && Danmakulistdata.lengTh () = 0) {for (int i = 0; i < danmakulistdata.length (); ++i) {try {JS                    Onobject e = Danmakulistdata.getjsonobject (i);                    if (E! = null) {Danmakus = This._parse (E, Danmakus);                }} catch (Jsonexception var5) {var5.printstacktrace ();        }} return Danmakus;        } else {return danmakus; }} private Danmakus _parse (Jsonobject jsonobject, Danmakus Danmakus) {if (Danmakus = = null) {DA        Nmakus = new Danmakus (); } if (Jsonobject! = null && jsonobject.length ()! = 0) {for (int i = 0; i < jsonobject.length ();                    ++i) {try {String c = jsonobject.getstring ("C");                    String[] values = C.split (","); if (Values.length > 0) {int type = Integer.parseint (VALUES[2]);                            if (type! = 7) {Long time = (long) (Float.parsefloat (values[0]) * 1000.0F); int color = Integer.parseint (values[1]) |                            -16777216;                            float textSize = float.parsefloat (values[3]);                            Basedanmaku item = This.mContext.mDanmakuFactory.createDanmaku (type, this.mcontext);                                if (item! = NULL) {Item.settime (time);                                Item.textsize = TextSize * (this.mdispdensity-0.6f);                                Item.textcolor = color; Item.textshadowcolor = Color <=-16777216?                                -1:-16777216;                                Danmakuutils.filltext (item, jsonobject.optstring ("M", "...."));                                Item.index = i;                                Item.settimer (This.mtimer);          Danmakus.additem (item);                  }}}} catch (Jsonexception Var13) {        } catch (NumberFormatException var14) {}} return Danmakus;        } else {return danmakus; }    }}

Android Bullet Screen realization: Based on the B-Station bullet screen Open source system (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.