Unity3D 生成&识别二维码

Unity扫描识别二维码

用WebCamTexture 获得摄像头数据,并把他付给UI层的RawImage.这个用来展示摄像头拍摄的内容画面。

private void CreateWebcamTex(string deviceName)
{
    mWebCamTexture = new WebCamTexture(deviceName,1280, 720);
    rawImage.texture = mWebCamTexture;
    mWebCamTexture.Play();
}

上面的函数需要传入 摄像头的名称,因为手机可能有前后置两个摄像头,需要选择后置摄像头的名称

WebCamDevice[] devices = WebCamTexture.devices; 
foreach (var item in devices){
     if(!item.isFrontFacing)
     {
           CreateWebcamTex(item.name);
           break;
    }   
}

zxing解析摄像头texture内容

    private BarcodeReader mReader;
    public string Decode(Color32[] colors, int width, int height)
    {
            var result = mReader.Decode(colors, width, height);
            if (result != null)
            {
                return result.Text;
            }
            return null;
    }

没必要每帧都去识别,可以每间隔0.2秒识别一次

    private IEnumerator Scan()
    {
            yield return new WaitForSeconds(0.2F);
            yield return new WaitForEndOfFrame();
            if (mWebCamTexture != null && mWebCamTexture.width > 100)
            {
                    string result = Decode(mWebCamTexture.GetPixels32(), mWebCamTexture.width, mWebCamTexture.height);
                    if(!string.IsNullOrEmpty(result)){
                            mWebCamTexture.Stop();
                            //识别成功后做相应操作
                    }else{
                        StartCoroutine(Scan());
                    }
            }

    }

生成二维码

对字符传进行二维码生成,返回的是Color32的数组

    private static Color32[] Encode(string textForEncoding, int width, int height)
    {
        var writer = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new QrCodeEncodingOptions
            {
                Height = height,
                Width = width,
                Margin = 2,
                PureBarcode = true
            }
        };
        return writer.Write(textForEncoding);
    }

将上面获得的Color32数组,设置到创建的Texture中,然后便可以在UI上显示出二维码图片了

Texture2D encoded = new Texture2D(200,200,TextureFormat.RGBA32,false);
var colors  = Encode("这里是二维码的内容",200,200);
encoded.SetPixels32(colors);
encoded.Apply();

更多unity2018的功能介绍请到paws3d爪爪学院查找。链接https://www.paws3d.com/learn/,也可以加入unity学习讨论群935714213

近期更有资深开发人士直播分享unity开发经验,详情请进入官网或加入QQ群了解

猜你喜欢

转载自blog.csdn.net/qq_35037137/article/details/89894170