Unity3D 生成二维码
---Jump 2014/9/4
使用ZXing的动态库,实现二维码生成:
1.调用GenerateQR(stringfilename)//filename QR的字符串信息
2.调用GetQR() //生成的二维码贴图
贴上代码:
using System.Threading;
using UnityEngine;
using ZXing;
using ZXing.QrCode;
public class BarcodeCam
{
//Texture for encoding test
public Texture2D encoded;
private WebCamTexture camTexture;
private Thread qrThread;
private Color32[] c;
private int W, H;
private Rect screenRect;
private bool isQuit;
public static string LastResult;
private bool shouldEncodeNow;
private static BarcodeCam instance = null;
private static readonly object syncObject = new object();
public static BarcodeCam GetInstance()
{
if (null == instance)
{
lock (syncObject)
{
if (null == instance)
{
instance = newBarcodeCam();
}
}
}
return instance;
}
void OnEnable()
{
if (camTexture != null)
{
camTexture.Play();
W = camTexture.width;
H = camTexture.height;
}
}
void OnDisable()
{
if (camTexture != null)
{
camTexture.Pause();
}
}
void OnDestroy()
{
qrThread.Abort();
camTexture.Stop();
}
//It's better to stop the thread by itself rather than abort it.
void OnApplicationQuit()
{
isQuit = true;
}
public void GenerateQR(string filename)
{
encoded = new Texture2D(256, 256);
LastResult = filename;
shouldEncodeNow = true;
screenRect = new Rect(0, 0, Screen.width, Screen.height);
camTexture = new WebCamTexture();
camTexture.requestedHeight = Screen.height; // 480;
camTexture.requestedWidth = Screen.width; //640;
OnEnable();
qrThread = new Thread(DecodeQR);
qrThread.Start();
if (c == null)
{
c = camTexture.GetPixels32();
}
// encode the last found
var textForEncoding = LastResult;
if (shouldEncodeNow &&
textForEncoding != null)
{
var color32 = Encode(textForEncoding, encoded.width, encoded.height);
encoded.SetPixels32(color32);
encoded.Apply();
shouldEncodeNow = false;
}
}
public Texture2D GetQR()
{
return encoded;
}
void DecodeQR()
{
// create a reader with a custom luminance source
var barcodeReader = new BarcodeReader {AutoRotate = false, TryHarder =false};
while (true)
{
if (isQuit)
break;
try
{
// decode the current frame
var result = barcodeReader.Decode(c, W, H);
if (result != null)
{
LastResult = result.Text;
shouldEncodeNow = true;
//print(result.Text);
}
// Sleep a little bit and set the signal to get the next frame
Thread.Sleep(200);
c = null;
}
catch
{
}
}
}
private static Color32[] Encode(string textForEncoding, int width, intheight)
{
var writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Height = height,
Width = width
}
};
return writer.Write(textForEncoding);
}
}