Orthographic camera movement clamping

I have an orthographic camera that is dynamically sized to give me pinch/zoom effects on a large background map. The camera’s position is also adjusted as you drag the map around.

What I need to do is prevent the camera from moving outside of our predetermined map area. Initially I thought I could just clamp the camera position, but the value that you need to clamp to is dependent on the camera’s current orthographicSize.

So the question is, how can I determine the current “bounding rectangle”(??) for an orthographic camera in world space? At first I thought it was simply the current camera location with the ortho size as an offset on all 4 sides, but that doesn’t seem to be accurate.

Adapted from this answer (and converted to c#), main difference for mine is that extents are moved into update to allow dynamic bounds with pinch and zoom:

 public class Camera_Bounds : MonoBehaviour 
    {
    	//mapX, mapY is size of background image
    	private float mapX = 61.4f; 
    	private float mapY = 41.4f;
    	private float minX;
    	private float maxX;
    	private float minY;
    	private float maxY;
    
    	void Update()
       	{
    		vertExtent = Camera.main.camera.orthographicSize;  
    		horzExtent = vertExtent * Screen.width / Screen.height;
    		
    	// Calculations assume map is position at the origin
    		minX = horzExtent - mapX / 2.0f;
    		maxX = mapX / 2.0f - horzExtent ;
    		minY = vertExtent - mapY / 2.0f;
    		maxY = mapY / 2.0f - vertExtent;
    	}
    
    	void LateUpdate() 
    	{
    		Vector3 v3 = transform.position;
    		v3.x = Mathf.Clamp(v3.x, minX, maxX);
    		v3.y = Mathf.Clamp(v3.y, minY, maxY);
    		transform.position = v3;
    	}	
    
    }

Below is the way I solved it in my project. The orthographical camera is set up so that it covers the entire background image at start. I use a reference camera (copy of the camera) that is set to not render anything. I use the reference camera to get unzoomed & unpanned size as well as getting correct focus point depending on view target position.

void LateUpdate()
{
    // get camera offset
    var offset = (_referenceCamera.WorldToViewportPoint(_cameraFocus.transform.position) - new Vector3(0.5f, 0.5f, 0.0f));

    // clamp offset depending on zoom
    float clamp = 0.5f - 0.5f / _cameraZoom;
    offset = new Vector3(Mathf.Clamp(offset.x, -clamp, clamp), Mathf.Clamp(offset.y, -clamp, clamp), offset.z);

    // pan camera
    var position = _referenceCamera.transform.position + new Vector3(offset.x * _referenceCamera.orthographicSize * 2.0f * camera.aspect, offset.y * _referenceCamera.orthographicSize * 2.0f, 0f);
    camera.transform.position = position; 

    // zoom camera
    camera.orthographicSize = _referenceCamera.orthographicSize / _cameraZoom;
}