Unity中Zxing生成二维码只能生成256大小图片的解决方案
Posted leesymbol
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity中Zxing生成二维码只能生成256大小图片的解决方案相关的知识,希望对你有一定的参考价值。
/// <summary> /// 生成2维码 方法 /// 经测试:能生成任意尺寸的正方形 /// </summary> /// <param name="content"></param> /// <param name="width"></param> /// <param name="height"></param> public static void GenerateQRCode2(string _qrcodeText, int _width, int _height, Action<Texture2D> _OnGenerateQRCode) { string qrcodeText = _qrcodeText; int width = _width; int height = _height; Action<Texture2D> OnGenerateQRCode = _OnGenerateQRCode; if (qrcodeText != null) { Loom.RunAsync(() => { try { // 编码成color32 MultiFormatWriter writer = new MultiFormatWriter(); Dictionary<EncodeHintType, object> hints = new Dictionary<EncodeHintType, object>(); hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.Add(EncodeHintType.MARGIN, 1); hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.M); BitMatrix bitMatrix = writer.encode(qrcodeText, BarcodeFormat.QR_CODE, width, height, hints); // 转成texture2d int w = bitMatrix.Width; int h = bitMatrix.Height; Color32[] color32 = Encode(qrcodeText, width, height); Loom.QueueOnMainThread(() => { Texture2D texture = new Texture2D(w, h); for (int x = 0; x < h; x++) { for (int y = 0; y < w; y++) { if (bitMatrix[x, y]) { //标志色 texture.SetPixel(y, x, Color.black); } else { //底色 texture.SetPixel(y, x, Color.white); } } } texture.Apply(); if (OnGenerateQRCode != null) { OnGenerateQRCode(texture); } }); } catch (Exception ex) { Loom.QueueOnMainThread(() => { Debug.Log("QRCodeHelper::GenerateQRCode - Exception : " + ex.ToString()); }); } }); } else { if (OnGenerateQRCode != null) { OnGenerateQRCode(null); } } }
解码:
public static void DecodeQRCode(Color32[] _data, int _width, int _height, Action<string> _OnDecodeQRCode) { Color32[] data = _data; int width = _width; int height = _height; Action<string> OnDecodeQRCode = _OnDecodeQRCode; Loom.RunAsync(() => { BarcodeReader barcodeReader = new BarcodeReader { AutoRotate = true }; barcodeReader.Options.TryHarder = true; try { // decode the current frame Result result = barcodeReader.Decode(data, width, height); Loom.QueueOnMainThread(() => { if (result != null) { if (OnDecodeQRCode != null) { OnDecodeQRCode(result.Text); } } else { if (OnDecodeQRCode != null) { OnDecodeQRCode(null); } } }); } catch { Loom.QueueOnMainThread(() => { if (OnDecodeQRCode != null) { OnDecodeQRCode(null); } }); } }); // create a reader with a custom luminance source }
private static Color32[] Encode(string textForEncoding, int width, int height) { BarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width } }; return writer.Write(textForEncoding); }
以上是关于Unity中Zxing生成二维码只能生成256大小图片的解决方案的主要内容,如果未能解决你的问题,请参考以下文章
zxing.unity.dll下载之后的位置找到UnityDemo/Assets下
java zxing实现二维码生成和解析zxing实现二维码生成和解析