unity Vuforia + 二维码解析 使用同一个摄像机

来源:互联网 发布:包天下网络怎么赚钱 编辑:程序博客网 时间:2024/05/16 12:32

在unity中,使用Vuforia并且实现同一相机扫描二维码。网上有几个教程,但是会遇到当应用被暂停以后二维码扫描不正确,主要原因来自于Vuforia的一个问题。查了很久才解决,在此记录,希望能帮到遇到同样问题的你们。


using UnityEngine;using System.Collections;using Vuforia;using ZXing;using ZXing.Client.Result;public class ScanCodeBehaviour : MonoBehaviour {        VuforiaBehaviour vuforia;    bool decoding;    bool init;    BarcodeReader barcodeReader = new BarcodeReader();    bool posting;    void Awake()    {        vuforia = this.GetComponent<VuforiaBehaviour>();        vuforia.RegisterTrackablesUpdatedCallback(OnTrackablesUpdated);    }    // Use this for initialization    void Start () {            }    void Update()    {        if (vuforia == null)            return;        if (vuforia.enabled && !init)        {            //Wait 1/4 seconds for the device to initialize (otherwise it seems to crash sometimes)              init = true;            Loom.QueueOnMainThread(() =>            {//这里必须先设置false,再设置true!!!                CameraDevice.Instance.SetFrameFormat(Vuforia.Image.PIXEL_FORMAT.RGB888, false);                init = CameraDevice.Instance.SetFrameFormat(Vuforia.Image.PIXEL_FORMAT.RGB888, true);                posting = false;            }, 0.25f);        }    }    void OnApplicationFocus(bool value)    {        if (value == false)        {        }        else        {//失去焦点后需要重新init            init = false;        }    }    public void Reinit()    {        init = false;    }    // Update is called once per frame    void OnTrackablesUpdated() {                if (vuforia.enabled && CameraDevice.Instance != null && !decoding && !posting)        {            Vuforia.Image image = CameraDevice.Instance.GetCameraImage(Vuforia.Image.PIXEL_FORMAT.RGB888);            if (image != null)            {                decoding = true;                                Loom.RunAsync(() =>                {                    try                    {                        Result data = barcodeReader.Decode(image.Pixels, image.BufferWidth, image.BufferHeight, RGBLuminanceSource.BitmapFormat.RGB24);                                                if (data != null)                        {                            Loom.QueueOnMainThread(() =>                            {                                Debug.LogError(data.Text);                                                            });                        }                    }                    finally                    {                        decoding = false;                    }                });            }        }    }   }

重点就两点,一点是应用失去焦点返回后需要重新init,第二是,重新init的时候需要把原有的format设置成false,不然不可用。。