赞
踩
在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,不然不可用。。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。