using System.Drawing.Drawing2D;
namespace Sunfish.WinForms;
/// <summary>
/// Imagenes de la interfaz (las de la 2.0, en Resources/), escaladas a los PPP de la pantalla
/// para que no queden diminutas en monitores con escalado.
/// </summary>
internal static class UiImages
{
private static readonly Dictionary<(string, int), Image> Cache = new();
public static float Scale { get; } = GetScale();
private static float GetScale()
{
using var g = Graphics.FromHwnd(IntPtr.Zero);
return Math.Max(1f, g.DpiX / 96f);
}
public static int Px(int size) => (int)Math.Round(size * Scale);
/// <summary>Imagen "nombre" (sin .png) a <paramref name="size"/> pixeles logicos.</summary>
public static Image Get(string name, int size = 16)
{
int px = Px(size);
if (Cache.TryGetValue((name, px), out var cached))
return cached;
using var stream = typeof(UiImages).Assembly.GetManifestResourceStream($"ui/{name}.png")
?? throw new InvalidOperationException("Missing image " + name);
using var original = Image.FromStream(stream);
var bitmap = new Bitmap(px, px);
using (var g = Graphics.FromImage(bitmap))
{
g.InterpolationMode = px % original.Width == 0 ? InterpolationMode.NearestNeighbor : InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.Half;
g.DrawImage(original, 0, 0, px, px);
}
Cache[(name, px)] = bitmap;
return bitmap;
}
/// <summary>Boton cuadrado solo con imagen y la descripcion como ayuda emergente.</summary>
public static Button IconButton(string image, string tooltip, ToolTip tips)
{
var button = new Button
{
Image = Get(image),
Size = new Size(26, 26),
UseVisualStyleBackColor = true,
AccessibleName = tooltip.Replace("&", ""),
};
tips.SetToolTip(button, tooltip.Replace("&", ""));
return button;
}
}