- 先将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 {
//定义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