BITKit/Packages/Runtime~/Unity/Extensions/ZXing/ZXingQR.cs

63 lines
2.3 KiB
C#
Raw Normal View History

2023-06-05 19:57:17 +08:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ZXing;
using ZXing.QrCode;
using Cysharp.Threading.Tasks;
using ZXing.Common;
namespace BITKit.UX.Components
{
[System.Serializable]
public class ZXingQRBuilder : StringComponent
{
public TranslateSO so;
public UXImage image;
protected override async void OnSet(string value)
{
var url = so.Get(value, false);
await UniTask.SwitchToMainThread();
var tex = GenerateQRImageWithColor(url, 256, 256, Color.black, out var bitMatrix);
image.Set(tex);
}
/// <param name="height"></param>
Texture2D GenerateQRImageWithColor(string content, int width, int height, Color color, out BitMatrix bitMatrix)
{
// 编码成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 = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
// 转成texture2d
int w = bitMatrix.Width;
int h = bitMatrix.Height;
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);
}
else
{
texture.SetPixel(y, x, Color.white);
}
}
}
texture.Apply();
//byte[] bytes = texture.EncodeToPNG();
//string path = System.IO.Path.Combine(Application.dataPath, "qr.png");
//System.IO.File.WriteAllBytes(path, bytes);
return texture;
}
}
}