I am currently trying to position some text in the center of a square drawn in a tikzpicture
, like so:
However, I am having a bit of trouble.
Take the following example:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{tikzpagenodes}
\usepackage{tikz}
\usepackage{calc}
\usepackage{layouts}
\begin{document}
\begin{tikzpicture}[overlay, remember picture, x=1cm, y=1cm]
\newcommand{\boxWidth}{5cm};
\newcommand{\boxHeight}{3cm};
\newcommand{\boxPosX}{5cm};
\newcommand{\boxPosY}{-5cm};
\newcommand{\someText}{Hello World};
\newcommand{\textPosX}{\boxPosX + (\printinunitsof{cm}\widthof{\someText}/2)};
\newcommand{\textPosY}{\boxPosY + \boxHeight / 2};
\draw [line width=0.05cm, rounded corners=.3cm, color=red] (\boxPosX,\boxPosY) rectangle ++(\boxWidth, \boxHeight);
\node at (\textPosX, \textPosY) {\someText};
\end{tikzpicture}
\end{document}
The problem arrises when I try using the width of the text: \widthof{\someText}/2
(from the calc
package). (Reference Post)
According to the same reference post, \widthof
returns a length in points, which is incompatible with centimeters. Therefore, I tried converting to centimeters by using the method described here: \printinunitsof{cm}\widthof{\someText}
.
However, this still yields an "Illegal unit of measure (pt inserted)."
What am I doing wrong and how can I correctly convert my units from points to centimeters?
tikzpicture
something which require so complicated code?\newcommand
, use\pgfmathsetmacro
instead, e.g.\pgfmathsetmacro{\textPosX}{\boxPosX + width("\someText")*1pt/2cm};
. But this is absolutely unnecessary here, as far as I can see.