首先我們需要下載.net版的zxing.net 庫
https://github.com/micjahn/ZXing.Net
下載下來之後,解壓 找到Unity版本的dll
也可以直接從這裡下載https://github.com/niyouwoxi/Unity3DQRCode/blob/master/Assets/zxing.unity.dll
Unity掃描識別二維碼
用WebCamTexture 獲得攝像頭數據,並把他付給UI層的RawImage.這個用來展示攝像頭拍攝的內容畫面。
private void CreateWebcamTex(string deviceName)
{
mWebCamTexture = new WebCamTexture(deviceName,1280, 720);
rawImage.texture = mWebCamTexture;
mWebCamTexture.Play();
}
上面的函數需要傳入 攝像頭的名稱,因為手機可能有前後置兩個攝像頭,我們需要選擇後置攝像頭的名稱
WebCamDevice[] devices = WebCamTexture.devices;
foreach (var item in devices){
if(!item.isFrontFacing)
{
CreateWebcamTex(item.name);
break;
}
}
zxing解析攝像頭texture內容
private BarcodeReader mReader;
public string Decode(Color32[] colors, int width, int height)
{
var result = mReader.Decode(colors, width, height);
if (result != null)
{
return result.Text;
}
return null;
}
沒必要每幀都去識別,可以每間隔0.2秒識別一次
private IEnumerator Scan()
{
yield return new WaitForSeconds(0.2F);
yield return new WaitForEndOfFrame();
if (mWebCamTexture != null && mWebCamTexture.width > 100)
{
string result = Decode(mWebCamTexture.GetPixels32(), mWebCamTexture.width, mWebCamTexture.height);
if(!string.IsNullOrEmpty(result)){
mWebCamTexture.Stop();
//識別成功後做相應操作
}else{
StartCoroutine(Scan());
}
}
}
生成二維碼
對字符傳進行二維碼生成,返回的是Color32的數組
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,
Margin = 2,
PureBarcode = true
}
};
return writer.Write(textForEncoding);
}
將上面獲得的Color32數組,設置到創建的Texture中,然後便可以在UI上顯示出二維碼圖片了
Texture2D encoded = new Texture2D(200,200,TextureFormat.RGBA32,false);
var colors = Encode("這裡是二維碼的內容",200,200);
encoded.SetPixels32(colors);
encoded.Apply();
完整代碼:https://github.com/niyouwoxi/Unity3DQRCode
閱讀更多 UnityAsk 的文章