项目中有一个需求是产品要通过激活码(二维码)来激活产品才能正常使用,之前为了快速推进项目一直是使用Metiao 来扫描二维码,由于metaio 被苹果收购之后不再是开源。支持的Unity版本只能到5.2,还有就是Android打包时如果SDK版本大于22,就会造成Android6.x以上版本安装出现错误。所以为了去掉这个雷区 用Unity扫描二维码:
1.下载ZXing.Net
2.把ZXing.net 中的Unity文件夹添加到Unity工程中
/*
* 生成二维码
*
*/
using UnityEngine;
using System.Collections.Generic;
using ZXing;
using ZXing.Common;
public class BarCodeScript : MonoBehaviour{
public Texture2D encoded;
void Start() {
encoded = new Texture2D(512, 512);
BitMatrix BIT;
string name = "https://www.baidu.com";
Dictionaryhints = new Dictionary();
hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
BIT = new MultiFormatWriter().encode(name, BarcodeFormat.QR_CODE, 512, 512, hints);
int width = BIT.Width;
int height = BIT.Width;
for (int x = 0; x < height; x++)
{
for (int y = 0; y < width; y++)
{
if (BIT[x, y])
{
encoded.SetPixel(y, x, Color.black);
}
else
{
encoded.SetPixel(y, x, Color.white);
}
}
}
encoded.Apply();
}
void OnGUI()
{
GUI.DrawTexture(new Rect(300, 100, 256, 256), encoded);
}
}
/*
* 二维码识别
*
*/
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using ZXing
public class QRcode : MonoBehaviour
{
public Color32[] data;
private bool isScan;
public RawImage cameraTexture;
public Text txtQrcode;
private WebCamTexture webCameraTexture;
private BarcodeReader barcodeReader;
private float timer = 0;
IEnumerator Start()
{
barcodeReader = new BarcodeReader();
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
string devicename = devices[0].name;
webCameraTexture = new WebCamTexture(devicename, 400, 300);
cameraTexture.texture = webCameraTexture;
webCameraTexture.Play();
isScan = true;
}
}
void Update()
{
if (isScan)
{
timer += Time.deltaTime;
if (timer > 0.5f) //0.5秒扫描一次
{
StartCoroutine(ScanQRcode());
timer = 0;
}
}
}
IEnumerator ScanQRcode()
{
data = webCameraTexture.GetPixels32();
DecodeQR(webCameraTexture.width, webCameraTexture.height);
yield return new WaitForEndOfFrame();
}
private void DecodeQR(int width, int height)
{
var br = barcodeReader.Decode(data, width, height);
if (br != null)
{
txtQrcode.text = br.Text;
isScan = false;
webCameraTexture.Stop();
}
}
}
网友评论