121 lines
5.7 KiB
C#
121 lines
5.7 KiB
C#
using System;
|
||
using System.IO;
|
||
using QRCoder;
|
||
using UnityEngine;
|
||
using Color = System.Drawing.Color;
|
||
|
||
namespace RR.Common.Utility
|
||
{
|
||
/// <summary>
|
||
/// Утилитарный класс для создания QR-кодов в Unity.
|
||
/// Предоставляет статические методы для генерации QR-кодов в виде текстур.
|
||
/// </summary>
|
||
public class QRMaker : MonoBehaviour
|
||
{
|
||
/// <summary>
|
||
/// Создает текстуру QR-кода из переданного текста.
|
||
/// </summary>
|
||
/// <param name="text">Текст или данные для кодирования в QR-код.</param>
|
||
/// <param name="pixelsPerModule">Количество пикселей на один модуль QR-кода. По умолчанию 8.</param>
|
||
/// <param name="drawQuietZones">Определяет, нужно ли рисовать тихие зоны (белые поля) вокруг QR-кода. По умолчанию true.</param>
|
||
/// <param name="darkColor">Темный цвет в QR-коде</param>
|
||
/// <param name="lightColor">Светлый цвет в QR-коде</param>
|
||
/// <returns>Texture2D с изображением QR-кода, готовая для использования в UI или материалах.</returns>
|
||
public static Texture2D MakeTexture(string text,
|
||
int pixelsPerModule = 8,
|
||
bool drawQuietZones = true,
|
||
Color darkColor = default,
|
||
Color lightColor = default)
|
||
{
|
||
Color dark = darkColor == default ? Color.Black : darkColor;
|
||
Color light = lightColor == default ? Color.White : lightColor;
|
||
|
||
QRCodeGenerator gen = new();
|
||
QRCoder.QRCodeData data = gen.CreateQrCode(text, QRCodeGenerator.ECCLevel.M);
|
||
|
||
PngByteQRCode png = new(data);
|
||
// Генерим PNG-байты с указанными цветами
|
||
byte[] bytes = png.GetGraphic(pixelsPerModule, dark, light, drawQuietZones);
|
||
|
||
Texture2D tex = new(150, 150, TextureFormat.RGBA32, false);
|
||
tex.LoadImage(bytes); // раскодирует PNG → RGBA
|
||
tex.Apply(false, false);
|
||
return tex;
|
||
}
|
||
|
||
// public static Texture2D MakeTexture(string text, Image icon = null, int pixelsPerModule = 8,
|
||
// bool drawQuietZones = true)
|
||
// {
|
||
// QRCodeGenerator gen = new();
|
||
// QRCoder.QRCodeData data = gen.CreateQrCode(text, QRCodeGenerator.ECCLevel.M);
|
||
// QRCode code = new(data);
|
||
// Bitmap bitmapIcon = code.GetGraphic(pixelsPerModule,
|
||
// Color.Black,
|
||
// Color.White,
|
||
// icon == null ? null : new Bitmap(icon),
|
||
// 15,
|
||
// 10,
|
||
// drawQuietZones);
|
||
// Texture2D tex = new(150, 150, TextureFormat.RGBA32, false);
|
||
// tex.LoadImage(bitmapIcon);
|
||
// }
|
||
|
||
// Сохранить как PNG-файл
|
||
public static string SavePng(string text, string filePath, int ppm = 8)
|
||
{
|
||
QRCodeGenerator gen = new();
|
||
QRCoder.QRCodeData data = gen.CreateQrCode(text, QRCodeGenerator.ECCLevel.M);
|
||
PngByteQRCode png = new PngByteQRCode(data);
|
||
byte[] bytes = png.GetGraphic(ppm, Color.Black, Color.White, true);
|
||
File.WriteAllBytes(filePath, bytes);
|
||
return filePath;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Структура данных для конфигурации генерации QR-кода.
|
||
/// Содержит параметры для создания полных ссылок с префиксом и суффиксом.
|
||
/// </summary>
|
||
[Serializable]
|
||
public struct QRCodeInfo
|
||
{
|
||
/// <summary>
|
||
/// Флаг, определяющий, нужно ли генерировать QR-код.
|
||
/// </summary>
|
||
public bool generateQRCode;
|
||
/// <summary>
|
||
/// Префикс ссылки (например, "https://example.com/").
|
||
/// </summary>
|
||
public string linkPrefix;
|
||
/// <summary>
|
||
/// Суффикс, добавляемый в качестве параметра запроса.
|
||
/// </summary>
|
||
public string suffix;
|
||
/// <summary>
|
||
/// Темный цвет в QR-коде.
|
||
/// </summary>
|
||
public Vector3 darkColor;
|
||
/// <summary>
|
||
/// Светлый цвет в QR-коде.
|
||
/// </summary>
|
||
public Vector3 lightColor;
|
||
|
||
public static Color GetColor(Vector3 colorRGB)
|
||
{
|
||
Color outColor = Color.FromArgb(255,
|
||
(int)(colorRGB.x * 255),
|
||
(int)(colorRGB.y * 255),
|
||
(int)(colorRGB.z * 255));
|
||
return outColor;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Формирует полную ссылку, объединяя префикс, данные и суффикс.
|
||
/// </summary>
|
||
/// <param name="data">Основные данные для включения в ссылку.</param>
|
||
/// <returns>Полная ссылка в формате: {linkPrefix}{data}?text={suffix}</returns>
|
||
public string GetFullLink(string data) => $"{linkPrefix}{data}?text={ProcessSuffix(suffix)}";
|
||
|
||
private string ProcessSuffix(string rawSuffix) => Uri.EscapeDataString(rawSuffix);
|
||
}
|
||
} |