Unity生成简易二维码

mac2022-06-30  36

最近项目需求,需要在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

 

转载于:https://www.cnblogs.com/Mr-Miracle/p/9273086.html

相关资源:unity版二维码生成库,附源码中间插图 示例
最新回复(0)