扫描二维码

二维码扫描

代码来自https://www.cnblogs.com/Feiyuzhu/p/6882096.html,这纯属我的备忘录,如有需要删除,请联系我.
首先 下载ZXing.Net.zip,下载地址为http://zxingnet.codeplex.com/。
解压找到unity文件夹,然后将其放到unity工程。
在这里插入图片描述

using UnityEngine;
using System.Collections;
using ZXing;
using UnityEngine.UI;
//解析二维码流程
//1.开启网络摄像头
//2.将摄像头的影像转换为原始格式的像素数据
//3.将像素数据和摄像头的高宽传入BarcodeReaderGeneric.Decode中
//4.BarcodeReaderGeneric.Decode会返回解析的数据,返回的数据包含String数据,这就是我们需要的
//5.与解析二维码无关,new 一个 WebCamTexture并赋给RawImage.texture可以看到摄像头的影像
public class QRCode : MonoBehaviour
{
    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))//检查用户是否已授权在Web播放器中使用网络摄像头或麦克风。
        {
            WebCamDevice[] devices = WebCamTexture.devices;//返回可用设备列表。
			if (devices.Length!=0)
			{
				string devicename = devices[0].name;//获取第一个可用设备
				webCameraTexture = new WebCamTexture(devicename, 400, 300);//创建一个网络摄像头的渲染图层
				cameraTexture.texture = webCameraTexture;//将网络摄像头的渲染图层在RawImage渲染出来
				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()
    {
        Color32[] data = webCameraTexture.GetPixels32();//从网络摄像头的渲染图层获得原始格式的像素数据。
        DecodeQR(data,webCameraTexture.width, webCameraTexture.height);
        yield return new WaitForEndOfFrame();
    }

    private void DecodeQR(Color32[] data,int width, int height)
    {
        var br = barcodeReader.Decode(data, width, height);//解码指定的二维码
        if (br != null)
        {
            txt.text = br.Text;
        }

    }

}

然后将代码随便挂那,电脑有摄像头的可以直接运行,不然就打包到手机上运行吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值