using Sunfish.Qr;
namespace Sunfish.WinForms;
/// <summary>Codigo QR de una direccion, para abrirla desde un movil. Pequena y sin redimensionar.</summary>
internal sealed class QrForm : Form
{
public QrForm(string url)
{
SuspendLayout();
AutoScaleDimensions = new SizeF(96F, 96F);
AutoScaleMode = AutoScaleMode.Dpi;
Text = Texts.QrTitle;
FormBorderStyle = FormBorderStyle.FixedToolWindow;
ShowInTaskbar = false;
BackColor = Color.White;
AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
Padding = new Padding(6);
var qr = QrCode.Encode(url);
int scale = Math.Max(3, UiImages.Px(5));
var picture = new PictureBox
{
Image = Render(qr, scale), SizeMode = PictureBoxSizeMode.AutoSize,
Location = new Point(Padding.Left, Padding.Top), Margin = new Padding(0),
};
var label = new Label
{
Text = url, AutoSize = true, MaximumSize = new Size(picture.Width, 0), ForeColor = Color.Black,
Location = new Point(Padding.Left, picture.Bottom + 4), Margin = new Padding(0),
};
Controls.AddRange([picture, label]);
ResumeLayout(false);
PerformLayout();
KeyPreview = true;
KeyDown += (_, e) =>
{
if (e.KeyCode == Keys.Escape)
Close();
};
}
/// <summary>Modulos negros sobre blanco con el margen de la norma; pixeles exactos, sin suavizar.</summary>
private static Bitmap Render(QrCode qr, int scale)
{
int size = (qr.Size + QrImage.QuietZone * 2) * scale;
var bitmap = new Bitmap(size, size);
using var g = Graphics.FromImage(bitmap);
g.Clear(Color.White);
for (int y = 0; y < qr.Size; y++)
for (int x = 0; x < qr.Size; x++)
if (qr[x, y])
g.FillRectangle(Brushes.Black, (x + QrImage.QuietZone) * scale, (y + QrImage.QuietZone) * scale, scale, scale);
return bitmap;
}
}