You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/labs/QrDemo/Assets/QRCode.cs

107 lines
3.1 KiB

using System;
using System.Collections;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using ZXing;
public class QRCode : MonoBehaviour
{
public RawImage rawImage;
private WebCamTexture webCamTexture;
private Color32[] data;
private BarcodeReader barcodeReader;
public Text text;
private int width;
private int height;
private int lastRotationAngle;
private RectTransform rectTransform;
private IEnumerator Start()
{
width = Screen.width;
height = Screen.height;
rectTransform = GetComponent<RectTransform>();
barcodeReader = new BarcodeReader();
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
var device = WebCamTexture.devices.FirstOrDefault(o => !o.isFrontFacing);
webCamTexture = new WebCamTexture(device.name, width, height, 25);
data = new Color32[webCamTexture.width * webCamTexture.height];
rawImage.texture = webCamTexture;
webCamTexture.Play();
//InvokeRepeating(nameof(CheckQRCode), 0, 1f);
}
}
private IEnumerator CheckQRCode()
{
yield return null;
if (webCamTexture != null && webCamTexture.isPlaying)
{
data = webCamTexture.GetPixels32();
if (data != null)
{
try
{
var tResult = barcodeReader.Decode(data, webCamTexture.width, webCamTexture.height);
if (tResult != null)
{
text.text = tResult.Text; //$"{tResult.BarcodeFormat}:{tResult.Text}";
}
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
}
}
}
}
private void OnEnable()
{
if (Application.HasUserAuthorization(UserAuthorization.WebCam) && webCamTexture != null)
{
webCamTexture.Play();
}
}
private void OnDisable()
{
if (Application.HasUserAuthorization(UserAuthorization.WebCam) && webCamTexture != null)
{
webCamTexture.Stop();
}
}
private void Update()
{
if (webCamTexture != null && lastRotationAngle != webCamTexture.videoRotationAngle)
{
OnOrientationChanged();
lastRotationAngle = webCamTexture.videoRotationAngle;
}
StartCoroutine(CheckQRCode());
}
private void OnOrientationChanged()
{
transform.localRotation = Quaternion.Euler(0, 0, -webCamTexture.videoRotationAngle);
//if (webCamTexture.videoRotationAngle % 180 != 0)
//{
// rectTransform.sizeDelta = new Vector2(height, width);
//}
//else
//{
// rectTransform.sizeDelta = new Vector2(width, height);
//}
}
private void OnGUI()
{
GUILayout.Label(webCamTexture.videoRotationAngle.ToString());
GUILayout.Label(webCamTexture.videoVerticallyMirrored.ToString());
}
}