在Unity中生成二维码

来源:互联网 发布:朝鲜水灾知乎 编辑:程序博客网 时间:2024/05/20 14:25

在Unity中生成二维码发现比较神奇,今天就在这里给大家分享下。

1.首先,http://zxingnet.codeplex.com/downloads/get/824664大家先去这里加载两个动态链接库,这是做二维码的核心。

2.把这两个*.dll文件存到我们以往用来存放的动态链接库的Plugins文件夹下。

3.把如下的代码放对象身上。

using UnityEngine;using System;using System.IO;using ZXing;using ZXing.QrCode;public class TwoDimesionCode : MonoBehaviour{ public Texture2D encoded;   //二维码贴图 public string Lastresult = "";  //生成二维码的信息 void Start() {  encoded = new Texture2D(256, 256);  //二维码图片大小 } /// <summary> ///根据二维码包含的信息以及宽高,对文本信息进行转码 /// </summary> /// <param name="textForEncoding"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> private static Color32[] Encode(string textForEncoding, int width, int height) {  BarcodeWriter writer = new BarcodeWriter  {   Format = BarcodeFormat.QR_CODE,   Options = new QrCodeEncodingOptions   {    Height = height,    Width = width   }  };  return writer.Write(textForEncoding); } void OnGUI() {  Lastresult = GUI.TextField(new Rect(10, 10, 150, 30), Lastresult);  //输入二维码包含信息  if (GUI.Button(new Rect(10, 45, 100, 30), "Draw"))  {   //绘制二维码   string textForEncoding = Lastresult;   if (textForEncoding != null)   {    Color32[] color32 = Encode(textForEncoding, encoded.width, encoded.height);    encoded.SetPixels32(color32);   //根据转换来的32位颜色值来计算二维码的像素    encoded.Apply();    //生成二维码   }  }  if (GUI.Button(new Rect(10, 80, 100, 30), "SaveEncode") && encoded != null)  {   try   {    byte[] pngData = encoded.EncodeToPNG();     //将Texture2D转码成png格式的字节数据    if (Application.platform == RuntimePlatform.Android)    {     File.WriteAllBytes(Application.persistentDataPath + "/" + Lastresult + "png", pngData);     //Android平台上保存的图片地址(一般保存在Android/data/com.***.***文件夹下)     GUI.Label(new Rect(Screen.width, Screen.height, Screen.width, Screen.height / 2), Application.persistentDataPath);    }    else    {     File.WriteAllBytes(Application.dataPath + "/TwoDimensionCode/" + Lastresult + ".png", pngData);     //非Android平台图片保存地址    }    print("save ok");   }   catch (Exception ioe)   {    Debug.LogException(ioe);    //输出图片保存异常信息   }  }  GUI.DrawTexture(new Rect(Screen.width / 2 - 128, Screen.height / 2 - 128, 256, 256), encoded);      //在屏幕上绘制出生成的二维码  if (GUI.Button(new Rect(10, 115, 100, 30), "Exit"))  {   Application.Quit();  } }}


1 0
原创粉丝点击