I’m trying to write a method that can move and resize a RectTransform to match another one, while leaving its pivot and anchoring intact. Rotation is not yet considered. Currently, I have this:
/// <summary>
/// Moves and resizes a RectTransform to match another one, while leaving its pivot and
/// anchoring intact.
/// </summary>
public static void Match(RectTransform src, RectTransform dst)
{
// Get dst world-space corners.
Vector3[] dstCorners = new Vector3[4];
dst.GetWorldCorners(dstCorners);
// Calculate dst world-space size and center from corners.
Vector2 dstSize = (Vector2)dstCorners[2] - (Vector2)dstCorners[0];
Vector2 dstCenter = (Vector2)dstCorners[0] + dstSize / 2f;
// Get src pivot location relative to src center.
Vector2 pivotOffset = src.pivot - Vector2.one * 0.5f;
// Check if src anchors are together on x and y axes (currently unused).
bool anchorsTogetherX = src.anchorMin.x == src.anchorMax.x;
bool anchorsTogetherY = src.anchorMin.y == src.anchorMax.y;
// Calculate src target position.
Vector2 targetPos = dstCenter + dstSize * pivotOffset;
// Set src position and size delta.
src.position = new Vector3(targetPos.x, targetPos.y, src.position.z);
src.sizeDelta = dstSize / src.lossyScale;
}
Which works well, except when the anchors of the src RectTransform are not together on the x and/or y axes. So in other words, the method doesn’t work for stretching anchor settings. RectTransforms end up much wider or taller than they should be, which makes sense, as the sizeDelta works differently in these cases (though It’s not entirely clear to me what exactly the variable does in these cases; the documentation is unfortunately a bit confusing for me).
Does anyone know how one should respond to the situations where the anchors are not placed together on one or both axes, so that the method will work for any anchoring setting (including custom ones)?