namespace Titano.Ui.Visuals;
/// Device-pixel alignment for drawn lines and edges (scale = device pixels per DIP).
public static class PixelGrid
{
/// Rounds to the nearest device-pixel boundary.
public static double Snap(double value, double scale)
{
if (!(scale > 0) || !double.IsFinite(value)) return value;
return Math.Round(value * scale) / scale;
}
///
/// Position of the centre of a line DIPs wide drawn at so it
/// covers whole device pixels: odd pixel widths sit on pixel centres, even ones on pixel boundaries.
///
public static double SnapLine(double value, double thickness, double scale)
{
if (!(scale > 0) || !double.IsFinite(value)) return value;
var pixels = Math.Max(1, Math.Round(thickness * scale));
var device = value * scale;
var snapped = pixels % 2 == 1 ? Math.Floor(device) + 0.5 : Math.Round(device);
return snapped / scale;
}
/// Line thickness in DIPs that renders as whole device pixels (at least one).
public static double SnapThickness(double thickness, double scale)
{
if (!(scale > 0)) return thickness;
return Math.Max(1, Math.Round(thickness * scale)) / scale;
}
}