/// <summary> /// Aligns target vertically and horisontally inside specified bounds. /// </summary> public static void Align(this DisplayObject target, Rect bounds, HAlign horizontal, VAlign vertical, bool snapToPixels = false) { var objectBounds = target.GetLocalBounds(); var x = objectBounds.x; var y = objectBounds.y; switch (horizontal) { case HAlign.LEFT: x = bounds.xMin; break; case HAlign.CENTER: x = 0.5f * (bounds.xMin + bounds.xMax - objectBounds.width); break; case HAlign.RIGHT: x = bounds.xMax - objectBounds.width; break; } switch (vertical) { case VAlign.TOP: y = bounds.yMin; break; case VAlign.MIDDLE: y = 0.5f * (bounds.yMin + bounds.yMax - objectBounds.height); break; case VAlign.BOTTOM: y = bounds.yMax - objectBounds.height; break; } target.x += x - objectBounds.xMin; target.y += y - objectBounds.yMin; if (snapToPixels) { target.position = target.position.RoundToInt(); } }
/// <summary> /// Adjusts position to ensure that object's bounds aren't outside the specified bounds /// </summary> public static void ClampBounds(this DisplayObject target, Rect bounds) { var rect = target.GetLocalBounds(); if (rect.xMin < bounds.xMin) { target.x += bounds.xMin - rect.xMin; } else if (rect.xMax > bounds.xMax) { target.x += bounds.xMax - rect.xMax; } if (rect.yMin < bounds.yMin) { target.y += bounds.yMin - rect.yMin; } else if (rect.yMax > bounds.yMax) { target.y += bounds.yMax - rect.yMax; } }