二维码 生成 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);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值