https://github.com/micjahn/ZXing.Net/releases/
在unity目录下找到zxing.unity.dll
[百度网盘] ZXing.Net.0.16.8.0.zip 提取码: fl91
也可以从这里直接下载 zxing.unity.dll
将zxing.unity.dll放到Unity工程下的Assets/Plugins目录下
发布到Hololens设备上进行测试。
可以使用草料二维码生成器生成测试二维码。
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.Serialization;
using ZXing;
/// <summary>
/// 扫描二维码辅助类
/// 基于 zxing.unity.dll
/// </summary>
public class QRCodeHelper : MonoBehaviour
{
//相机捕捉到的图像
private WebCamTexture webCameraTexture;
//ZXing中的类,可读取二维码的内容
private BarcodeReader barcodeReader;
//计时,0.5s扫描一次
private float scanInterval = 0.5f;
//存放摄像头画面数据
private Color32[] data;
//显示摄像头画面
public RawImage cameraTexture;
//显示二维码信息
public Text QRCodeText;
//是否正在扫描
private bool scaning;
//定义未找到设备相机事件
[Serializable]
public class NoCameraErrorEvent : UnityEvent { }
[FormerlySerializedAs("NoCameraError")]
[SerializeField]
private NoCameraErrorEvent m_NoCameraError = new NoCameraErrorEvent();
//定义扫码成功事件
public Action<string> OnCompleted;
//开始扫描二维码
public void StartScanQRCode()
{
StartCoroutine(RequestWebCamAuthorization());
}
//请求相机权限
IEnumerator RequestWebCamAuthorization()
{
barcodeReader = new BarcodeReader();
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//请求授权使用摄像头
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;//获取摄像头设备
if (devices.Length == 0)
{
Debug.LogError("device no camera available");
m_NoCameraError.Invoke();
yield break;
}
string devicename = devices[0].name;
webCameraTexture = new WebCamTexture(devicename, 400, 300);//获取摄像头捕捉到的画面
if (cameraTexture != null)
{
cameraTexture.enabled = true;
cameraTexture.texture = webCameraTexture;
}
webCameraTexture.Play();
StartCoroutine(ScanQRCode());
}
}
//扫描二维码
private IEnumerator ScanQRCode()
{
scaning = true;
while (true)
{
data = webCameraTexture.GetPixels32();//相机捕捉到的纹理
DecodeQR(webCameraTexture.width, webCameraTexture.height);
yield return new WaitForSeconds(scanInterval);
if (!scaning)
break;
}
}
/// <summary>
/// 识别二维码并显示其中包含的文字、URL等信息
/// </summary>
/// <param name="width">相机捕捉到的纹理的宽度</param>
/// <param name="height">相机捕捉到的纹理的高度</param>
private void DecodeQR(int width, int height)
{
var br = barcodeReader.Decode(data, width, height);
if (br != null)
{
//Debug.LogFormat("QR Code: {0}", br.Text);
if (QRCodeText != null)
QRCodeText.text = br.Text;
Stop();
OnCompleted?.Invoke(br.Text);
}
else
{
if (QRCodeText != null)
QRCodeText.text = "";
}
}
//停止扫描
public void Stop()
{
scaning = false;
}
}
官方提供的扫描二维码方案:Microsoft.MixedReality.QR