二维码扫描
代码来自https://www.cnblogs.com/Feiyuzhu/p/6882096.html,这纯属我的备忘录,如有需要删除,请联系我.
首先 下载ZXing.Net.zip,下载地址为http://zxingnet.codeplex.com/。
解压找到unity文件夹,然后将其放到unity工程。
using UnityEngine;
using System.Collections;
using ZXing;
using UnityEngine.UI;
//解析二维码流程
//1.开启网络摄像头
//2.将摄像头的影像转换为原始格式的像素数据
//3.将像素数据和摄像头的高宽传入BarcodeReaderGeneric.Decode中
//4.BarcodeReaderGeneric.Decode会返回解析的数据,返回的数据包含String数据,这就是我们需要的
//5.与解析二维码无关,new 一个 WebCamTexture并赋给RawImage.texture可以看到摄像头的影像
public class QRCode : MonoBehaviour
{
private bool 是否能扫描;
public RawImage cameraTexture;
public Text txt;
private WebCamTexture webCameraTexture;
private BarcodeReader barcodeReader;
private float timer = 0;
IEnumerator Start()
{
barcodeReader = new BarcodeReader();
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//
if (Application.HasUserAuthorization(UserAuthorization.WebCam))//检查用户是否已授权在Web播放器中使用网络摄像头或麦克风。
{
WebCamDevice[] devices = WebCamTexture.devices;//返回可用设备列表。
if (devices.Length!=0)
{
string devicename = devices[0].name;//获取第一个可用设备
webCameraTexture = new WebCamTexture(devicename, 400, 300);//创建一个网络摄像头的渲染图层
cameraTexture.texture = webCameraTexture;//将网络摄像头的渲染图层在RawImage渲染出来
webCameraTexture.Play();//启动相机。
是否能扫描 = true;
}
}
}
int width;
void ScreenChange()//屏幕横竖屏切换
{
if (width == Screen.width)
return;
width = Screen.width;
if (width > Screen.height)
{
cameraTexture.transform.localEulerAngles = Vector3.zero;
}
else
{
cameraTexture.transform.localEulerAngles = new Vector3(0, 0, -90);
}
}
void Update()
{
if (是否能扫描)
{
timer += Time.deltaTime;
if (timer > 0.5f) //0.5秒扫描一次
{
StartCoroutine(ScanQRcode());
timer = 0;
}
}
// ScreenChange();
}
IEnumerator ScanQRcode()
{
Color32[] data = webCameraTexture.GetPixels32();//从网络摄像头的渲染图层获得原始格式的像素数据。
DecodeQR(data,webCameraTexture.width, webCameraTexture.height);
yield return new WaitForEndOfFrame();
}
private void DecodeQR(Color32[] data,int width, int height)
{
var br = barcodeReader.Decode(data, width, height);//解码指定的二维码
if (br != null)
{
txt.text = br.Text;
}
}
}
然后将代码随便挂那,电脑有摄像头的可以直接运行,不然就打包到手机上运行吧