在网络上发现了一个可以把字符串转换成二维码的dll,但是我们要怎么使用他呢。不废话,直接进入主题。
用到的引用
using UnityEngine;
using ZXing;
using ZXing.QrCode;


1 private static Color32[] Encode(string textForEncoding, int width, int height) 2 { 3 var writer = new BarcodeWriter 4 { 5 Format = BarcodeFormat.QR_CODE, 6 Options = new QrCodeEncodingOptions 7 { 8 Height = height, 9 Width = width 10 } 11 }; 12 return writer.Write(textForEncoding); 13 }
如上面代码所示,dll给我们提供了一个方法,这个方法需要我们传人一段字符串和需要生成的色块的大小,他对应就会给我们生成一个二维码色块。当然有了色块,我们就可以和容易应用在Unity中了。
1 public Texture2D encoded;//生成出来的二维码图片 2 public Texture2D encoded1;//剪切后的二维码图片 3 string url = "www.baidu.com";//要生成的二维码字符串 4 void Start() 5 { 6 encoded = new Texture2D(256, 256);//创建一张图 7 UpdateQrCode(url); 8 } 9 public void UpdateQrCode(string QRSting) 10 { 11 if (QRSting == null || QRSting == "") 12 { 13 Debug.LogWarning(QRSting+" "); 14 QRSting = "www.baidu.com"; 15 } 16 string textForEncoding = QRSting; 17 if (textForEncoding != "") 18 { 19 Color32[] color = Encode(textForEncoding, encoded.width, encoded.height); 20 encoded.SetPixels32(color); 21 encoded.Apply(); 22 } 23 encoded1 = new Texture2D(222, 222);//创建目标图片大小 24 encoded1.SetPixels(encoded.GetPixels(17, 17, 222, 222));//获取对应的色块并设置在新的图片上 25 encoded1.Apply(); 26 transform.GetComponentInChildren<UITexture>().mainTexture = encoded1;//设置在Unity组件上 27 }
dll下载地址:http://files.cnblogs.com/files/jenke/%E4%BA%8C%E7%BB%B4%E7%A0%81dll.rar
亲测,安卓和苹果都可以使用