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

在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,不然不可用。。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值