using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using ZXing;
public class QRCodeReader : MonoBehaviour
{
public RawImage cameraImage;
private WebCamTexture camTexture;
private BarcodeReader barcodeRead;
private Thread threadReadQR;
Color32[] colorArr;
public int width;
public int height;
private bool IsFinishRead = false;
private string ResText;
public Text Text;
private void Start()
{
cameraImage.GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.height, Screen.width);
barcodeRead= new BarcodeReader();
StartCoroutine(OpenPhoneCamera());
}
private void Update()
{
if (colorArr == null && camTexture != null)
{
colorArr = camTexture.GetPixels32(); ;
}
if (IsFinishRead)
{
Text.text = ResText;
OpenURL(Text.text);
IsFinishRead = false;
}
}
/// <summary>
/// 打开手机摄像头
/// </summary>
/// <returns></returns>
public IEnumerator OpenPhoneCamera()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//请求打开手机摄像头权限,手机端会弹出一个选择弹窗
WebCamDevice[] devices = WebCamTexture.devices;
camTexture = new WebCamTexture(devices[0].name,Screen.width,Screen.height);
if (!camTexture.isPlaying|| camTexture==null)//解决第一次打开相机出线白屏问题
{
camTexture = new WebCamTexture(devices[0].name, Screen.width, Screen.height);
}
camTexture.Play();
cameraImage.texture = camTexture;
width = camTexture.width;
height = camTexture.height;
if (camTexture!=null&& camTexture.isPlaying)
{
threadReadQR = new Thread(DeCodeQR);//开启一个线程防止每次识别时候卡顿
threadReadQR.Start();
}
}
/// <summary>
/// 二维码识别
/// </summary>
public void DeCodeQR()
{
while (true)
{
if (colorArr!=null)
{
Result result = barcodeRead.Decode(colorArr, width, height);
if (result != null)
{
IsFinishRead = true;
ResText = result.Text;
}
Thread.Sleep(10);
colorArr = null;
}
}
}
public void OnDestroy()
{
threadReadQR.Abort();
Debug.Log("结束线程");
}
/// <summary>
/// 打开网页
/// </summary>
/// <param name="url"></param>
public void OpenURL(string url)
{
#if UNITY_EDITOR
Application.OpenURL(url);
#endif
#if !UNITY_EDITOR
Application.OpenURL("https://"+url);
#endif
}
}
相关代码插件链接:二维码生成以及读取