我这里用到GUI和UGUI来实现了一次,下载地址为http://zxingnet.codeplex.com/,我这里已经下载好了,引用一个zxing.unity.dll,下载网址https://pan.baidu.com/s/1Gs3t3CEFP4sroFs0Km7f8Q,
然后找到其中的unity文件夹,将文件夹放到Unity的工程内。创建一个Raw Image ,这里介绍一下,应为image不支持Texure2d图片,我这里生成的图片是这个,所以只能用Raw Image。将代码挂在物体上
具体代码:
- using UnityEngine;
- using System.Collections;
- using ZXing;//引入库
- using ZXing.QrCode;
- using UnityEngine.UI;
- public class BarcodeCam : MonoBehaviour
- {
- //定义Texture2D对象和用于对应网站的字符串
- public Texture2D encoded;
- public string Lastresult;
- //定义一个UI,来接收图片
- public RawImage ima;
- void Start()
- {
- encoded = new Texture2D(256, 256);
- Lastresult = "http://www.qq.com";
- }
- //定义方法生成二维码
- private static Color32[] Encode(string textForEncoding, int width, int height)
- {
- var writer = new BarcodeWriter
- {
- Format = BarcodeFormat.QR_CODE,
- Options = new QrCodeEncodingOptions
- {
- Height = height,
- Width = width
- }
- };
- return writer.Write(textForEncoding);
- }
- void Update()
- {
- var textForEncoding = Lastresult;
- if (textForEncoding != null)
- {
- //二维码写入图片
- var color32 = Encode(textForEncoding, encoded.width, encoded.height);
- encoded.SetPixels32(color32);
- encoded.Apply();
- //生成的二维码图片附给RawImage
- ima.texture = encoded;
- }
- }
- //将图片画出来
- void OnGUI()
- {
- GUI.DrawTexture(new Rect(100, 100, 256, 256), encoded);
- }
- }
运行unity之后效果图为
,如果大家觉得麻烦的话,可以去草料二维码上面直接生成你想要的内容,网址为 https://cli.im/text