unity之二維碼
阿新 • • 發佈:2020-08-13
首先下載外掛ZXing,連結在下面。解壓後把unity資料夾的檔案匯入unity中。
連結:https://pan.baidu.com/s/1_En2Tc2kdiDw8fvvzJZKYQ
提取碼:vl5k
程式碼如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using ZXing; using ZXing.QrCode; public class QRCodeManager { /// <summary> /// 直接返回圖片 /// </summary>/// <param name="textForEncoding"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="margin"></param> /// <returns></returns> public Texture2D GetTexture2D(string textForEncoding, int width, intheight, int margin) { if (textForEncoding == "") { Debug.Log("錯誤!資料不能為空字串!"); return null; } Texture2D t2d = new Texture2D(width, height); t2d.SetPixels32(GetQRcode(textForEncoding, width, height, margin)); t2d.Apply();return t2d; } /// <summary> /// 只返回生成二維碼的顏色資料 /// </summary> /// <param name="textForEncoding"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public Color32[] GetQRcode(string textForEncoding, int width, int height, int margin) { if (textForEncoding == "") { Debug.Log("錯誤!資料不能為空字串!"); return null; } BarcodeWriter writer = new BarcodeWriter //設定二維碼變數類 { Format = BarcodeFormat.QR_CODE, //設定二維碼格式 Options = new QrCodeEncodingOptions //設定編碼格式 { CharacterSet = "UTF-8",// 設定中文模式 Height = height, //設定寬高 Width = width, Margin = margin //設定二維碼的邊距 } }; return writer.Write(textForEncoding); } public ZXing.Result CheckQRCode(Texture2D t2d) { if (t2d == null) { Debug.Log("錯誤!圖片為空!"); return null; } Color32[] colorDatas = t2d.GetPixels32(); BarcodeReader m_barcodeRender = new BarcodeReader(); return m_barcodeRender.Decode(colorDatas, t2d.width, t2d.height);//將畫面中的二維碼資訊檢索出來 } }