- 先將ZXing.Net.0.16.4.0.zip下載下來,我用的版本是:v0.16.4.0
- 下載下來後解壓,將裏面的unity文件拷貝到unity項目下的plugins文件夾下
- 然後就是腳本了:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using ZXing;
using ZXing.QrCode;
public class QrCodeDraw : MonoBehaviour {
private Texture2D encoded;
private string Lastresult;
public RawImage ima;
void Start()
{
encoded = new Texture2D(256, 256);
Lastresult = "http://www.54ids.com";
}
void Encode(string content, int width, int height)
{
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);
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