立志成为理工男中最不像理工男的理工男。
最近需要做一个带有扫描二维码功能的程序,
需要用到两个 功能: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; } } }