我正在寻找一个打印当前 x 单位长度的宏。例如以下文档:
\documentclass[border=2pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[x=2cm,y=3cm]
\node at (0,0) {};
\end{tikzpicture}
\end{document}
现在我想要一个可以返回“x”的“2cm”或“y”的“3cm”的宏。
答案1
以下是使用该库的解决方案calc
:
\documentclass[border=2pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\def\getxlengthincm#1{
\path let \p{x}=(1,0), \n{xlencm}={scalar(veclen(\x{x},\y{x})/1cm)}
in \pgfextra{\xdef#1{\n{xlencm}}};
}
\begin{document}
\begin{tikzpicture}[x=2cm,y=3cm]
\getxlengthincm{\myxlength}
\node[align=center] at (0,0) {x length:\myxlength cm};
\end{tikzpicture}
\end{document}
这是一个具有明确pt
单位的变体:
\def\getxlength#1{
\path let \p{x}=(1,0), \n{xlen}={veclen(\x{x},\y{x})}
in \pgfextra{\xdef#1{\n{xlen}}};
}
答案2
使用printlen
包和https://tex.stackexchange.com/a/15996/36296
\documentclass[border=2pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{printlen}
\newlength{\pgfx}
\newlength{\pgfy}
\uselengthunit{cm}
\begin{document}
\begin{tikzpicture}[x=2cm,y=3cm]
\node at (0,0) {};
\pgfpointxy{1}{1};
\makeatletter
\setlength{\pgfx}{\pgf@x}
\setlength{\pgfy}{\pgf@y}
\makeatother
\node {\printlength{\pgfx}~\printlength{\pgfy}};
\end{tikzpicture}
\end{document}
答案3
\documentclass[border=2pt]{standalone}
\usepackage{tikz,luatex85,siunitx}
\makeatletter
\newcommand{\NodeDist}[3][\MyDist]{%
\pgfpointdiff{\pgfpointanchor{#2}{center}}
{\pgfpointanchor{#3}{center}}
% no need to use a new dimen
\pgf@xa=\pgf@x
\pgf@ya=\pgf@y
% to convert from pt to cm
\pgfmathparse{veclen(\pgf@xa,\pgf@ya)/28.45274}
\global\let#1\pgfmathresult % we need a global macro
}
\newcommand{\TZUnits}{
\coordinate (@0) at (0,0) ;
\coordinate (@X) at (1,0) ;
\coordinate (@Y) at (0,1) ;
\NodeDist[\Xunit]{@0}{@X}\edef\Xunit{\SI{\Xunit}{\cm}}
\NodeDist[\Yunit]{@0}{@Y}\edef\Yunit{\SI{\Yunit}{\cm}}
}
\makeatother
\begin{document}
\begin{tikzpicture}[x=2cm,y=3cm]
\TZUnits
\node {\Xunit~\Yunit};
\end{tikzpicture}
\end{document}