二維碼 生成 unity

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using System.IO;
using UnityEngine.UI;

#if UNITY_IPHONE || UNITY_EDITOR
using System.Runtime.InteropServices;
#endif


public class LiCommonTools{

    private static LiCommonTools mIns;

    public static LiCommonTools mInstance
    {
        get{
            if(mIns == null)
            {
                mIns = new LiCommonTools();
            }
            return mIns;
        }
    }

    private LiCommonTools()
    {
        mErWeiMaList.Clear();
    }

    #region  用於二維碼的使用
    private int myCurrentTankId =2;//初始tank ID 後面更換
    public  int MyCurrentTankId
    {
        get{
            return myCurrentTankId;
        }
        set
        {
            myCurrentTankId =value;
        }
    }

    //需要填充的二維碼信息 InitErWeiMa(string Content,int width,int height)直接獲得二維碼
    private string ErWeiMaContent="https://www.baidu.com";

    public string mErWeiMarContent{
        get{
            return ErWeiMaContent;
        }
        set{
            ErWeiMaContent=value;
        }
    }

    private int encoded_width; //二維碼的寬度
    private int encoded_height; //二維碼的高度

    //圖片名稱
    private string NeedErWeiMaName;

    //圖片具體路徑
    public string RootOfPicture
    {
        get{
            return RootOfFile+"/"+NeedErWeiMaName;
        }
    }

    //圖片具體路徑
    public string RootOfPictures
    {
        get{
            return RootOfFile+"/TankIcon";
        }
    }


    //圖片存儲路徑
    public string RootOfFile
    {
        get{
            return Application.persistentDataPath+"/lizhen";
        }
    }
    //優化  存儲需要生成二維碼的信息
    private Dictionary<string,Texture2D> mErWeiMaList=new Dictionary<string,Texture2D>();

    /// <summary>
    /// 用於生成二維碼並存儲
    /// </summary>
    /// <param name="Content">二維碼存儲的 需要的內容 </param>
    /// <param name="width">生成二維碼的寬度 </param>
    /// <param name="height">生成二維碼的高度</param>
    /// <param name="NeedName">生成二維碼的 名字  "name.png"</param>
    private void InitErWeiMa(string Content,int width,int height,string NeedName)
    {
        if(!Content.Equals(""))
        {
            //若不爲空 則賦值
            ErWeiMaContent = Content;
        }

        NeedErWeiMaName =NeedName;
        encoded_width = width;
        encoded_height = height;

        if(!mErWeiMaList.ContainsKey(ErWeiMaContent))
        {
            Texture2D encoded = new Texture2D(encoded_width, encoded_height);  //生成的二維碼爲Texture2D類型
            if (ErWeiMaContent != null)  
            {  
                Dictionary<EncodeHintType,System.Object> hints = new Dictionary<EncodeHintType, System.Object>();
                hints.Add(EncodeHintType.CHARACTER_SET,"utf-8");

                hints.Add(EncodeHintType.MARGIN,10);  ///去除白邊MAX_SIZE

                var color32 = Encode(ErWeiMaContent, encoded.width, encoded.height,hints);  


                Texture2D  logo = Resources.Load("Texture/Tanks/Littletank"+MyCurrentTankId.ToString())as Texture2D;
                var color32logo=logo.GetPixels32();

                int need_start=encoded_width/2-logo.width/2;
                int need_logo=logo.width;
                   
                    //像素 覆蓋
                for(int i=0;i<need_logo;i++)
                {
                    for(int j=0;j<need_logo;j++)
                    {
                      color32[(need_start+i)*encoded_width+j+need_start]=color32logo[i*need_logo+j];
                    }
                }


                encoded.SetPixels32(color32);  
                encoded.Apply();

                byte[] bytes = encoded.EncodeToPNG();//把二維碼轉成byte數組,然後進行輸出保存爲png圖片就可以保存下來生成好的二維碼 

                if (!Directory.Exists(RootOfFile))//創建生成目錄,如果不存在則創建目錄  
                {  
                    Directory.CreateDirectory(RootOfFile);
                }

                System.IO.File.WriteAllBytes(RootOfPicture, bytes);  
            }   
            mErWeiMaList.Add(ErWeiMaContent,encoded);
        }
    }

    private static Color32[] Encode(string textForEncoding, int width, int height,Dictionary<EncodeHintType, System.Object> strs)  
    {  
        var writer = new BarcodeWriter  
        {  
            Format = BarcodeFormat.QR_CODE,  
            Options = new QrCodeEncodingOptions  
            {  
                Height = height,  
                Width = width,
                Margin = 0
            }
        };  
        return writer.Write(textForEncoding);  
    }  

    //初始化與顯示不在同一時刻,獲得二維碼
    private Texture2D GetErWeiMa()
    { 
        if(mErWeiMaList.ContainsKey(ErWeiMaContent))
            return mErWeiMaList[ErWeiMaContent];
        else{
            return new Texture2D(encoded_width,encoded_height);
        }
    }

    //初始化與顯示在同一時刻   獲得二維碼
    public Texture2D GetErWeiMa(string Content,int width,int height,string NeedName)
    {
        InitErWeiMa(Content,width,height,NeedName);
        return GetErWeiMa();
    }
    #endregion

    #region 用於截圖保存到本地相冊 DealWithSaveToAlbums保存到相冊方法 通用
    #if UNITY_EDITOR || UNITY_IPHONE
    [DllImport("__Internal")]
    private static extern void _SavePhoto(string readAddr);
    #endif

    //IOS的方法用於存取圖片到IOS相冊
    private void SaveToIos()
    {
        #if UNITY_EDITOR || UNITY_IPHONE
        _SavePhoto(RootOfPicture);
        #endif
    }

    //Android的方法用於存取圖片到Android相冊
    private void SaveToAndroid()
    {
            //獲取系統時間並命名相片名
            System.DateTime now = System.DateTime.Now;
            string times = now.ToString ();
            times = times.Trim ();
            times = times.Replace ("/","-");
            string filename = "Screenshot"+times+".png";
            //判斷是否爲Android平臺
            if (Application.platform == RuntimePlatform.Android) {

                //截取屏幕
            //    Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);

            byte[] bytes= System.IO.File.ReadAllBytes(RootOfPicture);

                //texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
            //    texture.Apply();
                //轉爲字節數組
            //    byte[] bytes = texture.EncodeToPNG();

                string destinations = "/sdcard/DCIM/ARphoto";
                //判斷目錄是否存在,不存在則會創建目錄
                if (!Directory.Exists (destinations)) {
                    Directory.CreateDirectory (destinations);
                }
                string Path_save = destinations+"/" + filename;
                //存圖片
                System.IO.File.WriteAllBytes(Path_save, bytes);
            }
    }

    //用於存儲 當前截屏 於本地相冊中
    public void DealWithSaveToAlbums()
    {
        if(Application.platform == RuntimePlatform.IPhonePlayer)
        { 
            SaveToIos();
        }else if(Application.platform == RuntimePlatform.Android)
        {
            SaveToAndroid();
            GameobjectManager.Ins.ShowMessageTip("存儲成功!",GameUIManager.ins.uiRoot,true);
        }

    }
    #endregion

    #if UNITY_IPHONE
    [DllImport ("__Internal")]
    private static extern void _copyTextToClipboard(string text);
    #endif


    /// <summary>
    /// 用於通用 剪貼板的複製操作
    /// </summary>
    /// <param name="input">要複製的 內容</param>
    public void CopyToClipboard(string input)
    {
        #if UNITY_ANDROID
           // 對Android的調用
          AndroidJavaObject androidObject = new AndroidJavaObject("ClipboardTools"); 
          AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
          
          if (activity == null)  
            return;
          // 複製到剪貼板  
          androidObject.Call("copyTextToClipboard", activity, input);  
        #elif UNITY_IPHONE
          _copyTextToClipboard(input);
        #elif UNITY_EDITOR  
           TextEditor t = new TextEditor();  
           t.content = new GUIContent(input);  
           t.OnFocus();  
           t.Copy();  
        #endif  

        GameobjectManager.Ins.ShowMessageTip("複製成功!",GameUIManager.ins.uiRoot,true);
    }
}
發佈了26 篇原創文章 · 獲贊 3 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章