using Annulus;
using Azimuth;
using Glass;
namespace Konis.Testbed
{
///
/// A picture of a sprite on a backdrop, with its name beneath.
///
public class SpriteCell : Panel
{
///
/// The width and height of the square the picture is fitted into.
///
public const int PictureSide = 48;
private const double Gap = 2;
private readonly Panel backdrop;
private readonly Panel picture;
private readonly Vector pictureSize;
///
/// Returns the smallest size that holds a picture and a caption of .
///
public static Vector SizeFor(Vector captionSize)
{
var stack = new RectAggregator(new Vector(0, Gap));
stack.NewRow(PictureSide);
stack.NewRow(captionSize.Y);
return new Vector(Scalar.Max(PictureSide, captionSize.X), stack.Rect.Height);
}
///
/// Makes a cell of the smallest size that fits. The picture is scaled to fill the square it sits in without
/// changing its shape, and is owned from here on.
///
public SpriteCell(Glass.Material backdropMaterial, SpriteMaterial pictureMaterial, Label caption)
{
if (pictureMaterial == null)
{
throw new System.ArgumentNullException(nameof(pictureMaterial));
}
Caption = caption ?? throw new System.ArgumentNullException(nameof(caption));
Material = Glass.Material.Invisible;
AbsorbsMouse = false;
// The picture's shape decides which side of the square it fills.
Vector natural = pictureMaterial.PreferredSize(Constraints.Unbounded);
Constraints offer = natural.X >= natural.Y
? Constraints.TightWidth(PictureSide, PictureSide)
: Constraints.TightHeight(PictureSide, PictureSide);
pictureSize = pictureMaterial.PreferredSize(offer);
backdrop = new Panel { Material = backdropMaterial, AbsorbsMouse = false };
picture = new Panel { Material = pictureMaterial, AbsorbsMouse = false };
CanvasChildren.Add(backdrop);
CanvasChildren.Add(picture);
CanvasChildren.Add(caption);
Bounds = Rect.FromPositionAndSize(Vector.Zero, SizeFor(caption.Bounds.Size));
}
///
/// Gets the rect the picture fills, within the cell.
///
public Rect PictureBounds => picture.Bounds;
///
/// Gets the rect of the square behind the picture, within the cell.
///
public Rect BackdropBounds => backdrop.Bounds;
///
/// Gets the name beneath the picture.
///
public Label Caption { get; }
///
/// Puts the caption at the bottom and the picture in the middle of what is left, whatever the cell's size.
///
protected override void SizeChanged()
{
Rect remainder = CanvasRect;
Rect captionRow = remainder.NewRow(
Caption.Bounds.Height, VerticalJustification.Bottom, Gap, Shortfall.UseWhatIsLeft);
var square = new Vector(PictureSide, PictureSide);
Rect captionSlot = captionRow;
captionSlot.Center(Caption.Bounds.Size, Shortfall.UseWhatIsLeft);
Caption.Bounds = captionSlot;
Rect backdropSlot = remainder;
backdropSlot.Center(square, Shortfall.UseWhatIsLeft);
backdrop.Bounds = backdropSlot;
Rect pictureSlot = backdropSlot;
pictureSlot.Center(pictureSize, Shortfall.UseWhatIsLeft);
picture.Bounds = pictureSlot;
}
}
}