namespace Titano.Ui.Visuals;
/// Uniform scale and translation from image pixels to view units: view = image × + offset.
public readonly record struct ViewTransform(double Scale, double OffsetX, double OffsetY)
{
public (double X, double Y) ToView(double x, double y) => (x * Scale + OffsetX, y * Scale + OffsetY);
public (double X, double Y) ToImage(double x, double y) => ((x - OffsetX) / Scale, (y - OffsetY) / Scale);
}
/// Zoom and pan math of the preview: fit, zoom around a fixed point, panning limits and pixel alignment.
public static class ViewportMath
{
/// Largest scale at which the whole image fits the view (0 when either is empty).
public static double FitScale(double imageWidth, double imageHeight, double viewWidth, double viewHeight)
{
if (!(imageWidth > 0) || !(imageHeight > 0) || !(viewWidth > 0) || !(viewHeight > 0)) return 0;
return Math.Min(viewWidth / imageWidth, viewHeight / imageHeight);
}
/// The image at , centred in the view.
public static ViewTransform Centered(double scale, double imageWidth, double imageHeight, double viewWidth, double viewHeight) =>
new(scale, (viewWidth - imageWidth * scale) / 2, (viewHeight - imageHeight * scale) / 2);
///
/// Changes the scale to keeping the image point under (,
/// ) where it is.
///
public static ViewTransform ZoomAt(ViewTransform t, double scale, double viewX, double viewY)
{
if (!(t.Scale > 0) || !(scale > 0)) return t;
var k = scale / t.Scale;
return new ViewTransform(scale, viewX - (viewX - t.OffsetX) * k, viewY - (viewY - t.OffsetY) * k);
}
///
/// Keeps the image covering the view on each axis where it is larger than the view, and centred on each axis
/// where it is smaller, so panning can never lose the picture.
///
public static ViewTransform Clamp(ViewTransform t, double imageWidth, double imageHeight, double viewWidth, double viewHeight) =>
t with
{
OffsetX = ClampAxis(t.OffsetX, imageWidth * t.Scale, viewWidth),
OffsetY = ClampAxis(t.OffsetY, imageHeight * t.Scale, viewHeight),
};
/// Moves the offset by (, ) view units.
public static ViewTransform Pan(ViewTransform t, double dx, double dy) => t with { OffsetX = t.OffsetX + dx, OffsetY = t.OffsetY + dy };
/// Rounds the offset to whole device pixels ( device pixels per view unit) so 1:1 shows raw pixels.
public static ViewTransform SnapOffset(ViewTransform t, double pixelsPerUnit)
{
if (!(pixelsPerUnit > 0)) return t;
return t with
{
OffsetX = Math.Round(t.OffsetX * pixelsPerUnit) / pixelsPerUnit,
OffsetY = Math.Round(t.OffsetY * pixelsPerUnit) / pixelsPerUnit,
};
}
/// Next zoom level for a wheel movement of (positive = in), by a factor of 1.25 per notch.
public static double WheelZoom(double scale, double notches, double minScale, double maxScale) =>
Math.Clamp(scale * Math.Pow(1.25, notches), minScale, maxScale);
private static double ClampAxis(double offset, double size, double view)
{
if (size <= view) return (view - size) / 2;
return Math.Clamp(offset, view - size, 0);
}
}