using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ZXing;
using UnityEngine.UI;
/// <summary>
/// 二維碼掃描識別功能
/// </summary>
public class TestQRCodeScanning : MonoBehaviour {
[Header("攝像機檢測界面")]
public RawImage cameraTexture;//攝像機映射顯示區域
private WebCamTexture webCamTexture;//攝像機映射紋理
public Text text;//用來顯示掃描信息
//二維碼識別類
BarcodeReader barcodeReader;//庫文件的對象(二維碼信息保存的地方)
/// <summary>
/// 開啓攝像機和準備工作
/// </summary>
void DeviceInit()
{
//1、獲取所有攝像機硬件
WebCamDevice[] devices = WebCamTexture.devices;
//2、獲取第一個攝像機硬件的名稱
string deviceName = devices[0].name;//手機後置攝像機
//3、創建實例化一個攝像機顯示區域
webCamTexture = new WebCamTexture(deviceName, 400, 300);
//4、顯示的圖片信息
cameraTexture.texture = webCamTexture;
//5、打開攝像機運行識別
webCamTexture.Play();
//6、實例化識別二維碼信息存儲對象
barcodeReader = new BarcodeReader();
}
Color32[] data;//二維碼圖片信息以像素點顏色信息數組存放
/// <summary>
/// 識別攝像機圖片中的二維碼信息
/// 打印二維碼識別到的信息
/// </summary>
void ScanQRCode()
{
//7、獲取攝像機畫面的像素顏色數組信息
data = webCamTexture.GetPixels32();
//8、獲取圖片中的二維碼信息
Result result = barcodeReader.Decode(data,webCamTexture.width,webCamTexture.height);
//如果獲取到二維碼信息了,打印出來
if (result!=null)
{
Debug.Log(result.Text);//===》==》===》 這是從二維碼識別出來的信息
text.text = result.Text;//顯示掃描信息
//掃描成功之後的處理
IsScanning = false;
webCamTexture.Stop();
}
}
/// <summary>
/// Start 初始化函數
/// </summary>
private void Start()
{
scanningButton.onClick.AddListener(ScanningButtonClick);
}
bool IsScanning = false;
float interval = 3;//掃描識別時間間隔
[SerializeField] Button scanningButton;
void ScanningButtonClick()
{
DeviceInit();
IsScanning = true;
}
private void Update()
{
if (IsScanning)
{
//每隔一段時間進行一次識別二維碼信息
interval += Time.deltaTime;
if (interval>=3)
{
interval = 0;
ScanQRCode();//開始掃描
}
}
}
}