unity 生成二維碼

  1. 先將ZXing.Net.0.16.4.0.zip下載下來,我用的版本是:v0.16.4.0
  2. 下載下來後解壓,將裏面的unity文件拷貝到unity項目下的plugins文件夾下
  3. 然後就是腳本了:
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);
    }

}

參考:https://blog.csdn.net/anyuanlzh/article/details/78371535

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章