latextikz

How to compute radius with LaTeX/Tikz


I would like to define an ellipse in tikz which is included in a rectangle.

The tricky part is that I want that my drawing is automatically drawn from the variables of the top-left and bottom-right coordinates of the rectangle.

I can compute the center of the ellipse from the rectangle coordinate, but I fail to compute automatically the expected semi-major axis and semi-minor axis which are needed for the ellipse command.

Basically, I would like to compute (\xb-\xa)/2 and (\yb-\ya)/2

Do you have any idea ?

Thanks a lot :)

BR

What I've done so far :

\begin{tikzpicture}

% Top-left point coordinates
\newcommand\xa{0.75}
\newcommand\ya{2.25}

% Bottom-right point coordinates
\newcommand\xb{3.25}
\newcommand\yb{0.75}


\coordinate (A) at (\xa, \ya);
\coordinate (B) at (\xb, \yb);

\coordinate (C) at ($ 0.5*(A)+0.5*(B) $); % Center of the ellipse

\draw[thick, dashed] (A) rectangle (B);

%\draw[ultra thick] (C) ellipse ( ??? and ??? );
\end{tikzpicture}

Solution

  • Compute the semiaxes length using the sides of the rectangle.

    As you already noted, the semiaxes' lengths correspond to the halved sides of the rectangle. Down below you can find the code solving the problem.

    \documentclass{standalone}
    \usepackage{tikz}
    
    \usetikzlibrary{calc}
    \begin{document}
    \begin{tikzpicture}
    
    % Top-left point coordinates
    \newcommand\xa{0.75}
    \newcommand\ya{2.25}
    
    % Bottom-right point coordinates
    \newcommand\xb{3.25}
    \newcommand\yb{0.75}
    
    % Compute the semiaxes
    \def\a{abs(\xa-\xb)/2}
    \def\b{abs(\ya-\yb)/2}
    
    \coordinate (A) at (\xa, \ya);
    \coordinate (B) at (\xb, \yb);
    
    \coordinate (C) at ($ 0.5*(A)+0.5*(B) $); % Center of the ellipse
    
    \draw[thick, dashed] (A) rectangle (B);
    
    % Beware to put the length in curly brackets
    \draw[ultra thick] (C) ellipse ( {\a} and {\b} );
    \end{tikzpicture}
    \end{document}