Unity生成簡易二維碼


最近項目需求,需要在Unity中動態生成二維碼。所以就研究了一下,下面把動態生成二維碼的方法向大家分享一下。

第一種方法

需要一個 ZXing.dll文件。

下載地址我會在文章結尾給出。

直接將下載好的dll文件導入到Unity工程中即可,下面一起來看一下如何通過使用 ZXing.dll來生成二維碼吧。

創建一個場景,在場景中放置一個RawImage用來顯示二維碼。

接下來就編寫一個CreatQR.cs腳本掛載到Canvas上就可以了。直接上腳本:

這里要注意命名空間的引用。

 1 using System.Collections;  2 using System.Collections.Generic;  3 using UnityEngine;  4 using UnityEngine.UI;  5 using ZXing;  6 using ZXing.QrCode;  7 
 8 public class CreatQR : MonoBehaviour {  9 
10     //需要生產二維碼的字符串數組 
11     string[] QrCodeStr = { "https://www.baidu.com/", "https://www.cnblogs.com/Mr-Miracle/", "https://unity3d.com/cn", "https://www.sogou.com/" }; 12     //在屏幕上顯示二維碼 
13     public RawImage image; 14     //存放二維碼 
15  Texture2D encoded; 16     int Nmuber = 0; 17     // Use this for initialization 
18     void Start() 19  { 20         
21         encoded = new Texture2D(256, 256); 22  } 23 
24     // Update is called once per frame 
25     void Update() 26  { 27         if (Input.GetKeyDown(KeyCode.Space)) 28  { 29  Btn_CreatQr(); 30             Nmuber++; 31             if (Nmuber >= QrCodeStr.Length) 32  { 33                 Nmuber = 0; 34  } 35  } 36  } 37 
38     /// <summary>
39     /// 定義方法生成二維碼 40     /// </summary>
41     /// <param name="textForEncoding">需要生產二維碼的字符串</param>
42     /// <param name="width"></param>
43     /// <param name="height"></param>
44     /// <returns></returns>       
45     private static Color32[] Encode(string textForEncoding, int width, int height) 46  { 47         var writer = new BarcodeWriter 48  { 49             Format = BarcodeFormat.QR_CODE, 50             Options = new QrCodeEncodingOptions 51  { 52                 Height = height, 53                 Width = width 54  } 55  }; 56         return writer.Write(textForEncoding); 57  } 58 
59 
60     /// <summary>  
61     /// 生成二維碼 62     /// </summary>  
63     public void Btn_CreatQr() 64  { 65        
66         if (QrCodeStr[Nmuber].Length > 1) 67  { 68             //二維碼寫入圖片 
69             var color32 = Encode(QrCodeStr[Nmuber], encoded.width, encoded.height); 70  encoded.SetPixels32(color32); 71  encoded.Apply(); 72             //生成的二維碼圖片附給RawImage 
73             image.texture = encoded; 74  } 75         else
76  { 77             GameObject.Find("Text_1").GetComponent<Text>().text = "沒有生成信息"; 78  } 79  } 80 }

好啦,接下來看一下運行結果吧。

第二種方法。

自認為有點講述不太清楚,所以給大家一個網址,可以自行前往學習

學習第二種方法網址:在這里

第一種方法的dll文件及工程文件下載地址  鏈接:網盤下載地址 密碼:8djo

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM