Unity generates QR code

  1. First download ZXing.Net.0.16.4.0.zip, the version I use is: v0.16.4.0
  2. After downloading, unzip it, and copy the unity file inside to the plugins folder under the unity project
  3. Then there is the script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using ZXing;
using ZXing.QrCode;



public class QrCodeDraw : MonoBehaviour {


    //定义Texture2D对象和用于对应链接的字符串  
    private Texture2D encoded;
    private string Lastresult;
    //定义一个UI,来接收图片  
    public RawImage ima;

    void Start()
    {
        encoded = new Texture2D(256, 256);      
        Lastresult = "http://www.54ids.com";
    }

    //定义方法生成二维码  
    void Encode(string content, int width, int height)
    {

        // 编码成color32
        MultiFormatWriter writer = new MultiFormatWriter();
        Dictionary<EncodeHintType, object> hints = new Dictionary<EncodeHintType, object>();
        hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.Add(EncodeHintType.MARGIN, 1);
        hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.M);
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        // 转成texture2d
        int w = bitMatrix.Width;
        int h = bitMatrix.Height;
        Texture2D texture = new Texture2D(w, h);
        for (int x = 0; x < h; x++)
        {
            for (int y = 0; y < w; y++)
            {
                if (bitMatrix[x, y])
                {
                    texture.SetPixel(y, x, Color.black);
                }
                else
                {
                    texture.SetPixel(y, x, Color.white);
                }
            }
        }
        texture.Apply();
        ima.texture = texture;

    }

    //将图片画出来,将这个方法挂载在一个按钮上 
    public void OnGUIDraw()
    {
        Encode(Lastresult,512,512);
    }

}

Reference: https://blog.csdn.net/anyuanlzh/article/details/78371535

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324665536&siteId=291194637