1. <div id="f8mbs"></div>
        您好,歡迎來到源碼搜藏網!分享精神,快樂你我!
        [加入VIP] 設為首頁 | 收藏本站 | 網站地圖 | Sitemap | TAG標簽
      2. 首 頁
      3. 在線工具
      4. jquery手冊
      5. 當前位置:首頁 > 安卓源碼 > 技術博客 >

        Android創建自己的動態壁紙教程

        時間:2018-08-09 15:45 來源:互聯網 作者:源碼搜藏 瀏覽:收藏 挑錯 推薦 打印

        我在這篇文章中將描述我如何整理動態壁紙。 要創建動態壁紙,您需要設置以下內容 一個擴展 WallpaperService 并進一步實現擴展 Engine 類 的嵌套類的 類。 該類負責調用繪圖代碼。 顯示壁紙設置列表的活動。(可選)。 在這里,我發現了Android Preference A

        我在這篇文章中將描述我如何整理動態壁紙。

        Android創建自己的動態壁紙教程Android創建自己的動態壁紙教程Android創建自己的動態壁紙教程

        要創建動態壁紙,您需要設置以下內容

        1. 一個擴展WallpaperService 并進一步實現擴展Engine 的嵌套類的類。該類負責調用繪圖代碼。
        2. 顯示壁紙設置列表的活動。(可選)。在這里,我發現了Android Preference API,它可以輕松地為應用程序創建設置
        3. xml 文件夾中壁紙的XML定義
        4. 用于動態壁紙和偏好活動的AndroidManifest.xml條目。

        入門

        1.要創建動態壁紙,您必須在課程類中WallpaperService找到有關課程的更多信息,訪問https://developer.android.com/reference/android/service/wallpaper/WallpaperService.html

        該類必須覆蓋onCreateEngine()返回Engine 對象的  方法方法

        此外,此類必須具有擴展Engine 的嵌套類。(我不知道為什么)

        要創建下降動畫,我需要連續繪制表面。之前在使用canvas視圖invalidate() 方法時調用了更新視圖。但是在Engine課堂上沒有這樣的方法。要首先繪制效果,您需要從中獲取畫布getSurfaceHolder();

        之后,以特定間隔運行線程以更新繪圖表面。

        以下是動態skeleton壁紙類。

        package matrixlw.app.skd.wa;
        
        import android.content.Context;
        import android.content.SharedPreferences;
        import android.graphics.Canvas;
        import android.graphics.Color;
        import android.graphics.Paint;
        import android.os.Handler;
        import android.preference.PreferenceManager;
        import android.service.wallpaper.WallpaperService;
        import android.util.Log;
        import android.view.SurfaceHolder;
        
        import com.enrico.colorpicker.colorDialog;
        
        import java.util.Random;
        
        /**
         * Created by sapan on 1/10/2017.
         */
        
        public class matrixWall extends WallpaperService {
        
            private boolean mVisible;  // visible flag
            Canvas canvas;      // canvas reference
            int Drawspeed=10;   // thread call delay time
            Context mcontext;   //reference to the current context
        
           
        
            @Override
            public Engine onCreateEngine() {
                //set the Preference default value
                mcontext = this;  //set the current context
                
                //return the Engine Class
                return new LiveWall(); // this calls contain the wallpaper code
            }
        
        
            /*
            * this class extends the engine for the live wallpaper
            * THis class implements all the draw calls required to draw the wallpaper
            * This call is to neseted inside the wallpaper service class to function properly
            * don't know why though :(
             */
            public class LiveWall extends Engine
            {
        
                final Handler mHandler = new Handler(); // this is to handle the thread
        
                //the tread responsibe for drawing this thread get calls every time
                // drawspeed vars set the execution speed
                private final Runnable mDrawFrame = new Runnable() {
                    public void run() {
        
                      
                        // This method get called each time to drwaw thw frame
                        // Engine class does not provide any invlidate methods
                        // as used in canvas
                        // set your draw call here
                        drawFrame();
                    }
                };
        
        
                //Called when the surface is created
                @Override
                public void onSurfaceCreated(SurfaceHolder holder) {
                    super.onSurfaceCreated(holder);
        
                    //call the draw method
                    // this is where you must call your draw code
                    drawFrame();
        
                }
        
                // remove thread
                @Override
                public void onDestroy() {
                    super.onDestroy();
                    mHandler.removeCallbacks(mDrawFrame);
                }
        
        
                //called when varaible changed
                @Override
                public void onVisibilityChanged(boolean visible) {
                    mVisible = visible;
                    if (visible) {
                      
            //call the drawFunction
                        drawFrame();   
            
                    } else {
                        
                        //this is necessay to remove the call back
                        mHandler.removeCallbacks(mDrawFrame);
                    }
                }
        
                //called when surface destroyed
                @Override
                public void onSurfaceDestroyed(SurfaceHolder holder) {
                    super.onSurfaceDestroyed(holder);
                    mVisible = false;
                    //this is necessay to remove the call back
                    mHandler.removeCallbacks(mDrawFrame);
                }
        
        
        
          // my function which contain the code to draw
                //this function contain the the main draw call
                /// this function need to call every time the code is executed
                // the thread call this functioin with some delay "drawspeed"
                public void drawFrame()
                {
                    //getting the surface holder
                    final SurfaceHolder holder = getSurfaceHolder();
        
                    canvas = null;  // canvas
                    try {
                        canvas = holder.lockCanvas();  //get the canvas
                        if (canvas != null) {
                            // draw something
             // my draw code
                          
                        }
                    } finally {
                        if (canvas != null)
                            holder.unlockCanvasAndPost(canvas);
                    }
        
                    // Reschedule the next redraw
                    // this is the replacement for the invilidate funtion
                    // every time call the drawFrame to draw the matrix
                    mHandler.removeCallbacks(mDrawFrame);
                    if (mVisible) {
                        // set the execution delay
                        mHandler.postDelayed(mDrawFrame, Drawspeed);
                    }
                }
        
                @Override
                public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    super.onSurfaceChanged(holder, format, width, height);
                   // update when surface changed
        
                }
            }
        
        
        }

        2.創建xml定義。

        作為壁紙服務,必須在mywallpaper.xml等xml文件夾中創建xml文件

        Android創建自己的動態壁紙教程
        <?xml version="1.0" encoding="UTF-8"?>
        <wallpaper
        
            xmlns:android="http://schemas.android.com/apk/res/android"
        
            android:thumbnail="@mipmap/ic_launcher"
        
        
        
            android:settingsActivity="matrixlw.app.skd.wa.SettingsActivity"/>

        這里android:settingsActivity="matrixlw.app.skd.wa.SettingsActivity"/> 指向在動態壁紙預覽屏幕上單擊設置按鈕時調用的設置活動

        3. 必須正確設置android AndroidManifest.xml 以獲取運行此文件的動態壁紙。

        1. 設置功能
          <uses-feature android:name="android.software.live_wallpaper" />
        2. 添加壁紙和資源xml文件的服務。
          <service
                      android:name=".matrixWall"
                      android:enabled="true"
                      android:label="MATRIX RAIN"
                      android:permission="android.permission.BIND_WALLPAPER">
                      <intent-filter>
                          <action android:name="android.service.wallpaper.WallpaperService" />
                      </intent-filter>
          
                      <meta-data
                          android:name="android.service.wallpaper"
                          android:resource="@xml/mywallpaper"></meta-data>
                  </service>
        3. 添加設置活動
          <activity
                   android:name=".SettingsActivity"
                   android:label="@string/title_activity_settings"
                   android:exported="true">
                   <intent-filter>
                       <action android:name="android.intent.action.MAIN" />
                       <category android:name="android.intent.category.LAUNCHER" />
          
                   </intent-filter>
          
               </activity>
          

          android:exported="true" 必須設置此處,否則單擊設置按鈕時將不會打開此活動

        3.創建設置活動

        “設置”活動包含用于自定義動態壁紙屬性的UI。首選項活動是使用android首選項API創建的,這提供了一種創建首選項API的簡便方法

        有關詳細信息,請訪問:https//developer.android.com/guide/topics/ui/settings.html

        Color Picker是使用richocid創建的庫

        參考:https//github.com/enricocid/Color-picker-library

        我正在跳過設置活動。設置活動的文件和布局是SettingsActivity.java和xml / preferences。

        4.整理動態壁紙:

        矩陣雨效應將是我在我之前的文章中解釋過的動態壁紙。

        ref - 下面是該項目的抽獎代碼

        // ======== MATRIX LIVE WALLPAPER VARS
            int background_color= Color.parseColor("#FF000000");
            int text_color=Color.parseColor("#FF8BFF4A");
        
            int width = 1000000; //default initial width
            int height = 100; //default initial height
            int fontSize = 15; //font size of the text which will fall
            int columnSize = width/fontSize; //column size ; no of digit required to fill the screen
            int parentWidth;
            String text = "MATRIXRAIN";  // Text which need to be drawn
            char[] textChar = text.toCharArray(); // split the character of the text
            int textLength = textChar.length;   //length of the length text
            Random rand = new Random(); //random generater
        
            int[]  textPosition; // contain the position which will help to draw the text
            //======================
        
          //old matrix effect code
            void drawText()
            {
                //Set up the paint
                Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(text_color);
                paint.setTextSize(15);
        
        
                //loop and paint
                for(int i =0 ;i<textPosition.length;i++)
                {
                    // draw the text at the random position
                    canvas.drawText(""+textChar[rand.nextInt(textLength)+0],i*fontSize,textPosition[i]*fontSize,paint);
                    // check if text has reached bottom or not
                    if(textPosition[i]*fontSize > height && Math.random() > 0.975)
                        textPosition[i] = 0;   // change text position to zero when 0 when text is at the bottom
        
                    textPosition[i]++; //increment the position array
                }
            }
        
            //old martix effect code
            public void canvasDraw()
            {
                Log.d("canvas ","drawing");
                //set the paint for the canvas
                Paint paint = new Paint();
                paint.setColor(background_color);
        
                paint.setAlpha(5);
                paint.setStyle(Paint.Style.FILL);
                canvas.drawRect(0, 0, width, height, paint);//draw rect to clear the canvas
        
                drawText(); // draw the canvas
        
            }

        現在上面的代碼需要插入到骨架壁紙服務代碼中。在skeleton類中,DrawFrame()方法用于調用draw語句。

        package matrixlw.app.skd.wa;
        
        import android.content.Context;
        import android.content.SharedPreferences;
        import android.graphics.Canvas;
        import android.graphics.Color;
        import android.graphics.Paint;
        import android.os.Handler;
        import android.preference.PreferenceManager;
        import android.service.wallpaper.WallpaperService;
        import android.util.Log;
        import android.view.SurfaceHolder;
        
        import com.enrico.colorpicker.colorDialog;
        
        import java.util.Random;
        
        /**
         * Created by sapan on 1/10/2017.
         */
        
        public class matrixWall extends WallpaperService {
        
            private boolean mVisible;  // visible flag
            Canvas canvas;      // canvas reference
            int Drawspeed=10;   // thread call delay time
            Context mcontext;   //reference to the current context
        
            // ======== MATRIX LIVE WALLPAPER VARS
            int background_color= Color.parseColor("#FF000000");
            int text_color=Color.parseColor("#FF8BFF4A");
        
            int width = 1000000; //default initial width
            int height = 100; //default initial height
            int fontSize = 15; //font size of the text which will fall
            int columnSize = width/fontSize; //column size ; no of digit required to fill the screen
            int parentWidth;
            String text = "MATRIXRAIN";  // Text which need to be drawn
            char[] textChar = text.toCharArray(); // split the character of the text
            int textLength = textChar.length;   //length of the length text
            Random rand = new Random(); //random generater
        
            int[]  textPosition; // contain the position which will help to draw the text
            //======================
        
            @Override
            public Engine onCreateEngine() {
                //set the Preference default value
                mcontext = this;  //set the current context
        
                //Initalise and read the preference
                PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
        
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
                text = sharedPref.getString("matrix_scroll_text", "MATRIX");
                Drawspeed = Integer.parseInt(sharedPref.getString("matrix_falling_speed","10"));
                fontSize = Integer.parseInt(sharedPref.getString("matrix_font_size","15"));
                background_color = colorDialog.getPickerColor(getBaseContext(), 1);
                text_color =colorDialog.getPickerColor(getBaseContext(), 2);
        
                //Some loggers Commnet or remove if you want
                Log.d("back_color",""+background_color);
                Log.d("text_color",""+text_color);
        
                textChar = text.toCharArray(); // split the character of the text
                textLength = textChar.length;
                columnSize = width/fontSize;
        
                //return the Engine Class
                return new LiveWall(); // this calls contain the wallpaper code
            }
        
        
            /*
            * this class extends the engine for the live wallpaper
            * THis class implements all the draw calls required to draw the wallpaper
            * This call is to neseted inside the wallpaper service class to function properly
            * don't know why though :(
             */
            public class LiveWall extends Engine
            {
        
                final Handler mHandler = new Handler(); // this is to handle the thread
        
                //the tread responsibe for drawing this thread get calls every time
                // drawspeed vars set the execution speed
                private final Runnable mDrawFrame = new Runnable() {
                    public void run() {
        
                        //Matrix code to the color when changed
                        // callback can also be used but I havent
                        background_color = colorDialog.getPickerColor(getBaseContext(), 1);
                        text_color =colorDialog.getPickerColor(getBaseContext(), 2);
                        // ^^^^^^^^
        
                        // This method get called each time to drwaw thw frame
                        // Engine class does not provide any invlidate methods
                        // as used in canvas
                        // set your draw call here
                        drawFrame();
                    }
                };
        
        
                //Called when the surface is created
                @Override
                public void onSurfaceCreated(SurfaceHolder holder) {
                    super.onSurfaceCreated(holder);
        
                    //update  the matrix variables
                    width = getDesiredMinimumWidth();
                    height = getDesiredMinimumHeight();
                    columnSize = width/fontSize;
                    //initalise the textposiotn to zero
                    textPosition = new int[columnSize+1]; //add one more drop
                    for(int x = 0; x < columnSize; x++) {
                        textPosition[x] = 1;
                    }
                    //^^^^^^^^^^^^^^^
        
                    //call the draw method
                    // this is where you must call your draw code
                    drawFrame();
        
                }
        
                // remove thread
                @Override
                public void onDestroy() {
                    super.onDestroy();
                    mHandler.removeCallbacks(mDrawFrame);
                }
        
        
                //called when varaible changed
                @Override
                public void onVisibilityChanged(boolean visible) {
                    mVisible = visible;
                    if (visible) {
                        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mcontext);
                        text = sharedPref.getString("matrix_scroll_text", "MATRIX");
                        Drawspeed = Integer.parseInt(sharedPref.getString("matrix_falling_speed","10"));
                        fontSize = Integer.parseInt(sharedPref.getString("matrix_font_size","15"));
                        background_color = colorDialog.getPickerColor(getBaseContext(), 1);
                        text_color =colorDialog.getPickerColor(getBaseContext(), 2);
        
        
        
                        textChar = text.toCharArray(); // split the character of the text
                        textLength = textChar.length;
                        columnSize = width/fontSize;
                        drawFrame();
                    } else {
                        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mcontext);
                        text = sharedPref.getString("matrix_scroll_text", "MATRIX");
                        Drawspeed = Integer.parseInt(sharedPref.getString("matrix_falling_speed","10"));
                        fontSize = Integer.parseInt(sharedPref.getString("matrix_font_size","15"));
                        background_color = colorDialog.getPickerColor(getBaseContext(), 1);
                        text_color =colorDialog.getPickerColor(getBaseContext(), 2);
        
        
        
                        textChar = text.toCharArray(); // split the character of the text
                        textLength = textChar.length;
                        columnSize = width/fontSize;
        
                        //this is necessay to remove the call back
                        mHandler.removeCallbacks(mDrawFrame);
                    }
                }
        
                //called when surface destroyed
                @Override
                public void onSurfaceDestroyed(SurfaceHolder holder) {
                    super.onSurfaceDestroyed(holder);
                    mVisible = false;
                    //this is necessay to remove the call back
                    mHandler.removeCallbacks(mDrawFrame);
                }
        
        
        
                //this function contain the the main draw call
                /// this function need to call every time the code is executed
                // the thread call this functioin with some delay "drawspeed"
                public void drawFrame()
                {
                    //getting the surface holder
                    final SurfaceHolder holder = getSurfaceHolder();
        
                    canvas = null;  // canvas
                    try {
                        canvas = holder.lockCanvas();  //get the canvas
                        if (canvas != null) {
                            // draw something
        
                            // canvas matrix draw code
                            canvasDraw();
                            //^^^^
                        }
                    } finally {
                        if (canvas != null)
                            holder.unlockCanvasAndPost(canvas);
                    }
        
                    // Reschedule the next redraw
                    // this is the replacement for the invilidate funtion
                    // every time call the drawFrame to draw the matrix
                    mHandler.removeCallbacks(mDrawFrame);
                    if (mVisible) {
                        // set the execution delay
                        mHandler.postDelayed(mDrawFrame, Drawspeed);
                    }
                }
        
        
        
        
        
        
                @Override
                public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    super.onSurfaceChanged(holder, format, width, height);
        
                    // some matrix variable
                    // though not needed
                    Paint paint = new Paint();
                    paint.setColor(background_color);
                    paint.setAlpha(255); //set the alpha
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawRect(0, 0, width, height, paint);
        
                }
            }
        
        
            //old matrix effect code
            void drawText()
            {
                //Set up the paint
                Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(text_color);
                paint.setTextSize(15);
        
        
                //loop and paint
                for(int i =0 ;i<textPosition.length;i++)
                {
                    // draw the text at the random position
                    canvas.drawText(""+textChar[rand.nextInt(textLength)+0],i*fontSize,textPosition[i]*fontSize,paint);
                    // check if text has reached bottom or not
                    if(textPosition[i]*fontSize > height && Math.random() > 0.975)
                        textPosition[i] = 0;   // change text position to zero when 0 when text is at the bottom
        
                    textPosition[i]++; //increment the position array
                }
            }
        
            //old martix effect code
            public void canvasDraw()
            {
                Log.d("canvas ","drawing");
                //set the paint for the canvas
                Paint paint = new Paint();
                paint.setColor(background_color);
        
                paint.setAlpha(5);
                paint.setStyle(Paint.Style.FILL);
                canvas.drawRect(0, 0, width, height, paint);//draw rect to clear the canvas
        
                drawText(); // draw the canvas
        
            }
        
        
        }

        這里使用以下方法來設置表面

        public void onSurfaceCreated(SurfaceHolder holder)
         public void onVisibilityChanged(boolean visible)
         public void onSurfaceDestroyed(SurfaceHolder holder)
         public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height)

        現在你有完整的工作動態壁紙代碼。

        獲取源表單:https//github.com/sapandang/Matrix-Rain-Live-Wallpaper

        Android創建自己的動態壁紙教程轉載http://www.rhcg.tw/appboke/38815.html
        標簽:網站源碼
        下一篇:沒有了
        辽宁十一选五单双