using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using ZXing;
using ZXing.QrCode;
public class CreatQR : MonoBehaviour {
//需要生產二維碼的字符串數組
string[] QrCodeStr = { "ni hao , shi jie.Hello World,lkasdljasdklfjsdlkfjl;asdjf;lkdsjfl;jalksdjal;ksdjalsdj " };
//在屏幕上顯示二維碼
public RawImage image;
//存放二維碼
Texture2D encoded;
int Nmuber = 0;
// Use this for initialization
void Start()
{
encoded = new Texture2D(256, 256);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Btn_CreatQr();
Nmuber++;
if (Nmuber >= QrCodeStr.Length)
{
Nmuber = 0;
}
}
}
/// <summary>
/// 定義方法生成二維碼
/// </summary>
/// <param name="textForEncoding">需要生產二維碼的字符串</param>
/// <param name="width">寬</param>
/// <param name="height">高</param>
/// <returns></returns>
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,
CharacterSet = "UTF-8"
}
};
return writer.Write(textForEncoding);
}
/// <summary>
/// 生成二維碼
/// </summary>
public void Btn_CreatQr()
{
if (QrCodeStr[Nmuber].Length > 1)
{
//二維碼寫入圖片
var color32 = Encode(QrCodeStr[Nmuber], encoded.width, encoded.height);
encoded.SetPixels32(color32);
encoded.Apply();
//生成的二維碼圖片附給RawImage
image.texture = encoded;
}
else
{
GameObject.Find("Text_1").GetComponent<Text>().text = "沒有生成信息";
}
}
}
利用zixing生成,支持中文。下載資源解壓放在plugin文件夾。