【Unity】在Unity中实现二维码扫描功能(扫描、生成)

在Unity中使用二维码扫描功能需要我们在Unty中导入扫描库

下载地址:https://github.com/micjahn/ZXing.Net/releases

然后编写扫描脚本:

先在脚本上添加引用:

using ZXing;
using ZXing.QrCode;

功能脚本:

//摄像头实时显示的画面
private WebCamTexture m_webCameraTexture;
 //申请一个读取二维码的变量
private BarcodeReader m_barcodeRender = new BarcodeReader();

//多久检索一次二维码
private float m_delayTime = 3f;


void Start()
    {
        //调用摄像头并将画面显示在屏幕RawImage上
        WebCamDevice[] tDevices = WebCamTexture.devices; //获取所有摄像头
        string tDeviceName = tDevices[0].name; //获取第一个摄像头,用第一个摄像头的画面生成图片信息
        m_webCameraTexture = new WebCamTexture(tDeviceName, 400, 300); //名字,宽,高
        m_cameraTexture.texture = m_webCameraTexture; //赋值图片信息
        m_webCameraTexture.Play(); //开始实时显示
        InvokeRepeating("CheckQRCode", 0, m_delayTime);
    }

    /// 
    /// 检索二维码方法
    /// 
    void CheckQRCode()
    {
        //存储摄像头画面信息贴图转换的颜色数组
        Color32[] m_colorData = m_webCameraTexture.GetPixels32();

        //将画面中的二维码信息检索出来
        var tResult = m_barcodeRender.Decode(m_colorData, m_webCameraTexture.width, m_webCameraTexture.height);

        if (tResult != null)
        {
            Debug.Log(tResult.Text);
        }
    }

结果在下:

【Unity】在Unity中实现二维码扫描功能(扫描、生成)_第1张图片

 上面是扫描的脚本,下面写生成二维码代码:

添加引用:

using ZXing;
using ZXing.QrCode;

 功能性脚本:

//用于显示生成的二维码RawImage
public RawImage m_QRCode;

//申请一个写二维码的变量
private BarcodeWriter m_barcodeWriter;

//启动方法
/////////////////////////////////
ShowQRCode("FransicZhang的博客", 256, 256);
/////////////////////////////////



    /// 
    /// 显示绘制的二维码
    /// 
    /// 扫码信息
    /// 码宽
    /// 码高
    void ShowQRCode(string s_str, int s_width, int s_height)
    {
        //定义Texture2D并且填充
        Texture2D tTexture = new Texture2D(s_width, s_height);

        //绘制相对应的贴图纹理
        tTexture.SetPixels32(GeneQRCode(s_str, s_width, s_height));

        tTexture.Apply();

        //赋值贴图
        m_QRCode.texture = tTexture;
    }

    /// 
    /// 返回对应颜色数组
    /// 
    /// 扫码信息
    /// 码宽
    /// 码高
    Color32[] GeneQRCode(string s_formatStr, int s_width, int s_height)
    {
        //设置中文编码格式,否则中文不支持
        QrCodeEncodingOptions tOptions = new QrCodeEncodingOptions();
        tOptions.CharacterSet = "UTF-8";
        //设置宽高
        tOptions.Width = s_width;
        tOptions.Height = s_height;
        //设置二维码距离边缘的空白距离
        tOptions.Margin = 3;

        //重置申请写二维码变量类       (参数为:码格式(二维码、条形码...)    编码格式(支持的编码格式)    )
        m_barcodeWriter = new BarcodeWriter {Format = BarcodeFormat.QR_CODE, Options = tOptions};

        //将咱们需要隐藏在码后面的信息赋值上
        return m_barcodeWriter.Write(s_formatStr);
    }

效果图:

【Unity】在Unity中实现二维码扫描功能(扫描、生成)_第2张图片

你可能感兴趣的:(Unity,二维码,unity,Unity黑科技实验室)