在Unity中生成二維碼

在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();
  }
 }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章