Unity 掃描識別二維碼


立志成為理工男中最不像理工男的理工男

 最近需要做一個帶有掃描二維碼功能的程序,

需要用到兩個 功能:1,打開手機硬件的攝像頭。2,調用二維碼識別功能。

其中遇到的bug:

手機或程序如果有橫豎屏切換,則會影響相機拍攝的圖片的角度(旋轉了90度)

所以在update里判斷了一下是否切換了橫豎屏,如果切換了,則圖片旋轉90度。

 

如有不明白,

歡迎加微信公眾號 “哎呦還不錯喔”  后台討論。

需要先在網上下一個zxing.unity.dll放在工程里

代碼如下:

using UnityEngine;
using System.Collections;
using ZXing;
using UnityEngine.UI;

public class cam : MonoBehaviour
{
    public Color32[] data;
    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))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            string devicename = devices[0].name;
            webCameraTexture = new WebCamTexture(devicename, 400, 300);
            cameraTexture.texture = webCameraTexture;
            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()
    {
        data = webCameraTexture.GetPixels32();
        DecodeQR(webCameraTexture.width, webCameraTexture.height);
        yield return new WaitForEndOfFrame();
    }

    private void DecodeQR(int width, int height)
    {
        var br = barcodeReader.Decode(data, width, height);
        if (br != null)
        {
            txt.text = br.Text;
           // isScan = false;
           
        }

    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM