Files
Fonepay-Unity/Packages/com.voidbotz.fonepayunity/Runtime/QR/FonepayQRGenerator.cs
2026-05-07 14:27:36 +05:45

67 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using UnityEngine;
namespace Darkmatter.Fonepay
{
/// <summary>
/// Pure C# QR Code generator. Byte mode, ECC L/M/Q/H, versions 110.
/// </summary>
public static partial class FonepayQRGenerator
{
public enum EccLevel { L, M, Q, H }
public static Texture2D GenerateTexture(string text, int pixelSize = 10,
EccLevel ecc = EccLevel.M, Color? darkColor = null, Color? lightColor = null)
{
bool[,] matrix = GenerateMatrix(text, ecc);
int size = matrix.GetLength(0);
int texSize = size * pixelSize;
var tex = new Texture2D(texSize, texSize, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Point,
wrapMode = TextureWrapMode.Clamp
};
Color dark = darkColor ?? Color.black;
Color light = lightColor ?? Color.white;
for (int row = 0; row < size; row++)
for (int col = 0; col < size; col++)
{
Color c = matrix[row, col] ? dark : light;
for (int py = 0; py < pixelSize; py++)
for (int px = 0; px < pixelSize; px++)
tex.SetPixel(col * pixelSize + px,
(size - 1 - row) * pixelSize + py, c);
}
tex.Apply();
return tex;
}
public static Sprite GenerateSprite(string text, int pixelSize = 10,
EccLevel ecc = EccLevel.M, Color? darkColor = null, Color? lightColor = null,
float pixelsPerUnit = 100f)
{
var tex = GenerateTexture(text, pixelSize, ecc, darkColor, lightColor);
var sprite = Sprite.Create(tex,
new Rect(0, 0, tex.width, tex.height),
new Vector2(0.5f, 0.5f),
pixelsPerUnit,
0, SpriteMeshType.FullRect);
sprite.name = "FonepayQR";
return sprite;
}
public static bool[,] GenerateMatrix(string text, EccLevel ecc = EccLevel.M)
{
if (string.IsNullOrEmpty(text))
throw new System.ArgumentException("QR text must be non-empty", nameof(text));
byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
var (version, ecBlocks) = ChooseVersion(data.Length, ecc);
byte[] codewords = BuildCodewords(data, version, ecc, ecBlocks);
return BuildMatrix(version, codewords);
}
}
}