如果我使用 提取坐标\pgfgetlastxy{}{}
,我会得到根据我对绘制应用的变换(旋转、缩放)而变化的结果:
\documentclass[margin=0.5cm]{standalone}
\usepackage{tikz}
\newcommand{\myDraw}[2]{%
\begin{minipage}[t]{6cm}
\centering #1,#2\\
\begin{tikzpicture}[#1,#2]
\draw[->] (0,0) -- (3,0);
\draw[->] (0,0) -- (0,3);
\coordinate (A) at (1,3);
\draw[blue] (A) node {$+$} node[above right] {\footnotesize A(2,3)};
\path (A); \pgfgetlastxy{\xA}{\yA}; % Extract the coordinates of A
\draw[red] (canvas cs:x=\xA,y=\yA)
node {$+$} node[red,below right] {\parbox{2.5cm}{\footnotesize \textbackslash xA = \xA\\\textbackslash yA = \yA}};
\end{tikzpicture}
\end{minipage}}
\begin{document}
\myDraw{scale=1}{rotate=0}
\myDraw{scale=0.5}{rotate=0}
\myDraw{scale=1}{rotate=-20}
\end{document}
然而,我想获取当前范围内 A 的坐标(即上例中的\xA
= 1 和\yA
= 3),因为我需要稍后应用一些条件(例如“if \xA < \xb then...”)。
我当时想也许可以使用类似组内的命令\pgftransformreset
,然后将未转换的坐标“偷运”出组。但我主要是 LaTeX/TikZ 最终用户,我不知道如何实现这一点。
答案1
由于内部转换的介入,数字略有扭曲。
\documentclass[margin=0.5cm]{standalone}
\usepackage{tikz}
\makeatletter
\newcommand{\myDraw}[2]{%
\begin{minipage}[t]{6cm}
\centering #1,#2\\
\begin{tikzpicture}[#1,#2]
\draw[->] (0,0) -- (3,0);
\draw[->] (0,0) -- (0,3);
\coordinate (A) at (1,3);
\draw[blue] (A) node {$+$} node[above right] {\footnotesize A(2,3)};
\pgfpointanchor{A}{center} %<----
\edef\xa{\the\pgf@x}
\edef\ya{\the\pgf@y} %<----
\draw[red] (canvas cs:x=\xa,y=\ya)
node {$+$} node[red,below right] {\parbox{2.5cm}{\footnotesize%
\textbackslash xA = \xa\\\textbackslash yA = \ya}};
\end{tikzpicture}
\end{minipage}}
\makeatother
\begin{document}
\myDraw{scale=1}{rotate=0}
\myDraw{scale=0.5}{rotate=0}
\myDraw{scale=1}{rotate=-20}
\end{document}
标记的代码可以用更高级别的 TikZ 语法替换
\path (A); \pgfgetlastxy{\xA}{\yA}; % Extract the coordinates of A
\begin{scope}
\pgftransforminvert
\coordinate (B) at (\xA,\yA);\path (B); \pgfgetlastxy{\xB}{\yB};
\xdef\xorigA{\xB}
\xdef\yorigA{\yB}
\end{scope}
其作用大致相同。
答案2
这里有一个解决方案,不需要低级宏\pgfgetlastxy
,只需通过let
操作即可:
\documentclass[margin=0.5cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\newcommand{\myDraw}[2]{%
\begin{minipage}[t]{6cm}
\centering #1,#2\\
\begin{tikzpicture}[#1,#2]
\draw[->] (0,0) -- (3,0);
\draw[->] (0,0) -- (0,3);
\coordinate (A) at (1,3);
\draw[blue] (A) node {$+$} node[above right] {\footnotesize A(2,3)};
\path [green!50!black]
let \p1=(A) in
(\x1,\y1) node {$+$}
node[below right,align=left,font=\footnotesize]{
\textbackslash xA = \x1\\
\textbackslash yA = \y1
};
\end{tikzpicture}
\end{minipage}}
\begin{document}
\myDraw{scale=1}{rotate=0}
\myDraw{scale=0.5}{rotate=0}
\myDraw{scale=1}{rotate=-20}
\end{document}
如果在路径及其let
操作之后需要这些宏定义,您可以:
- 使用
\xdef
:
\path let \p1=(A) in
\pgfextra{
\xdef\xA{\x1}
\xdef\yA{\y1}
};
- 使用
\AfterGroup
(来自etextools
包装):
\usepackage{etextools}
...
\path let \p1=(A) in
\pgfextra{
\AfterGroup*{
\noexpand\def\noexpand\xA{\x1}
\noexpand\def\noexpand\yA{\y1}
}
};