Unity二维码生成FairyGUI显示
发表于2018-09-18
本篇来看看如何在Unity中实现二维码生成FairyGUI显示,具体的步骤如下:
1.下载Zxing
2.生成二维码图。
/// <summary> /// 绘制二维码 /// </summary> /// <param name="s_formatStr">扫码信息</param> /// <param name="s_width">码宽</param> /// <param name="s_height">码高</param> public static Texture2D CreateQRCode(string s_str, int s_width, int s_height) { //定义Texture2D并且填充 Texture2D tTexture = new Texture2D(s_width, s_height); //绘制相对应的贴图纹理 tTexture.SetPixels32(GeneQRCode(s_str, s_width, s_height)); tTexture.Apply(); return tTexture; } /// <summary> /// 返回对应颜色数组 /// </summary> /// <param name="s_formatStr">扫码信息</param> /// <param name="s_width">码宽</param> /// <param name="s_height">码高</param> static Color32[] GeneQRCode(string s_formatStr, int s_width, int s_height) { //设置中文编码格式,否则中文不支持 QrCodeEncodingOptions tOptions = new QrCodeEncodingOptions(); tOptions.CharacterSet = "UTF-8"; //设置宽高 tOptions.Width = s_width; tOptions.Height = s_height; //设置二维码距离边缘的空白距离 tOptions.Margin = 3; //重置申请写二维码变量类 (参数为:码格式(二维码、条形码...) 编码格式(支持的编码格式) ) BarcodeWriter m_barcodeWriter = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = tOptions }; //将咱们需要隐藏在码后面的信息赋值上 return m_barcodeWriter.Write(s_formatStr); }
3.显示在UI上:
Texture2D encoded = encoded = QRCodeHelp.CreateQRCode("星 12123 sd", 256, 256); panel.m_testImage.texture = new NTexture(encoded);
4.扫描
//二维码识别生成控制类 public class QRCode : MonoBehaviour { #region 扫描二维码 //摄像头实时显示的画面 private WebCamTexture m_webCameraTexture; //申请一个读取二维码的变量 private BarcodeReader m_barcodeRender = new BarcodeReader(); public Action<string> QRsuccess; bool isQRing = false; public float m_QRRepTime =3f; #endregion /// <summary> /// 扫码 /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="QRRepTime"></param> /// <returns></returns> public WebCamTexture StartQRCode(int width,int height) { if (isQRing == true) { Debug.Log("正在扫描====="); return null; } //调用摄像头并将画面显示在屏幕RawImage上 WebCamDevice[] tDevices = WebCamTexture.devices; //获取所有摄像头 if (tDevices.Length <= 0) { Debug.LogError("没有摄像头!"); return null; } Debug.Log("length:" + tDevices.Length); string tDeviceName = tDevices[0].name; //获取第一个摄像头,用第一个摄像头的画面生成图片信息 m_webCameraTexture = new WebCamTexture(tDeviceName, width, height);//名字,宽,高 m_webCameraTexture.Play(); //开始实时显示 isQRing = true; InvokeRepeating("CheckQRCode", 1, m_QRRepTime); return m_webCameraTexture; } public void StopQR() { m_webCameraTexture.Stop(); m_webCameraTexture = null; CancelInvoke(); isQRing = false; } /// <summary> /// 检索二维码方法 /// </summary> void CheckQRCode() { //存储摄像头画面信息贴图转换的颜色数组 Color32[] m_colorData = m_webCameraTexture.GetPixels32(); //将画面中的二维码信息检索出来 var tResult = m_barcodeRender.Decode(m_colorData, m_webCameraTexture.width, m_webCameraTexture.height); if (tResult != null && QRsuccess != null) { QRsuccess(tResult.Text); } }
来自:https://blog.csdn.net/u010665359/article/details/79141910