Unity自动创建二维码功能
Unity自动创建二维码功能
给到连接或者信息,动态生成二维码,并自带保存功能。下面是dll连接:https://pan.baidu.com/s/16s5Y9kw-nKcpM3TT3uebPw
Unity自动创建二维码功能
代码
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using ZXing;
using ZXing.QrCode;
public class CreatQR : MonoBehaviour
{
//在屏幕上显示二维码
public RawImage image;
//存放二维码
Texture2D encoded;
// Use this for initialization
void Start()
{
encoded = new Texture2D(256, 256);
}
///
/// 定义方法生成二维码
///
/// 需要生产二维码的字符串
/// 宽
/// 高
///
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
}
};
return writer.Write(textForEncoding);
}
/// <summary>
/// 生成二维码
/// </summary>
public void Btn_CreatQr(string id)
{
//二维码写入图片
var color32 = Encode(id, encoded.width, encoded.height);
encoded.SetPixels32(color32);
encoded.Apply();
//生成的二维码图片附给RawImage
image.texture = encoded;
}
private string filespath = Application.streamingAssetsPath + "/EWM/";
//储存二维码图片
void DoPicture(string name)//存储为png
{
if (!Directory.Exists(filespath + name+".png"))//首先判断一下该图片文件是否存在
{
Directory.CreateDirectory(filespath + name+".png");//创建目录
var bys = encoded.EncodeToPNG();//转换图片资源
File.WriteAllBytes(filespath, bys);//保存图片到写好的目录下
}
}
}