Files
cppk-ar/Assets/Scripts/QRCodeReader.cs
T
2022-11-09 13:30:45 +05:00

108 lines
2.8 KiB
C#

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using ZXing;
using UnityEngine;
using UnityEngine.UI;
public class QRCodeReader : MonoBehaviour
{
public static QRCodeReader Instance { get; private set; }
public event Action<string> OnQRCodeRead;
[SerializeField] AspectRatioFitter aspectRatioFitter;
public RawImage rawImage;
public GameObject scanFrame;
public WebCamTexture camTexture;
private Coroutine c_QRScanningRoutine;
void Start()
{
Instance = this;
int backCameraId = 0;
bool backCameraEnabled = false;
List<int> backCameraIDs = new List<int>();
WebCamDevice[] devices = WebCamTexture.devices;
if(devices.Length != 0)
{
for(int i = 0; i < devices.Length; i++)
{
if(Application.platform == RuntimePlatform.Android && !devices[i].isFrontFacing)
{
backCameraEnabled = true;
backCameraIDs.Add(i);
}
else
{
backCameraEnabled = true;
backCameraId = 0;
}
}
if(backCameraIDs.Count != 0)
backCameraId = backCameraIDs.First();
}
if(!backCameraEnabled) return;
camTexture = new WebCamTexture(devices[backCameraId].name);
rawImage.texture = camTexture;
camTexture.Play();
int orientation = -camTexture.videoRotationAngle;
rawImage.rectTransform.localEulerAngles = Vector3.forward * orientation;
var ratio = (float)camTexture.width / (float)camTexture.height;
aspectRatioFitter.aspectRatio = ratio;
float scaleY = camTexture.videoVerticallyMirrored ? -1f : 1f;
rawImage.rectTransform.localScale = new Vector3(1f, scaleY, 1f);
ScanningQRCode();
}
public void ScanningQRCode()
{
if(c_QRScanningRoutine != null)
{
StopCoroutine(c_QRScanningRoutine);
c_QRScanningRoutine = null;
}
c_QRScanningRoutine = StartCoroutine(ScanQRCode());
}
IEnumerator ScanQRCode()
{
Result result;
while(true)
{
try
{
IBarcodeReader barcodeReader = new BarcodeReader();
result = barcodeReader.Decode
(
camTexture.GetPixels32(),
camTexture.width,
camTexture.height
);
if(result != null) break;
}
catch { }
yield return new WaitForSeconds(.5f);
}
yield return new WaitForSeconds(1);
OnQRCodeRead?.Invoke(result.Text);
}
}