Tikz 在縮放圖片中的節點文字中顯示座標

Tikz 在縮放圖片中的節點文字中顯示座標

想要顯示座標值,但是使用下面的方法,該值無法準確列印出來。

嘗試使用以下方法檢索量表恢復 TikZ 中的比例因子然後使用比例因子值,如提取TikZ中任意點的x、y座標。然而,@scalefactor 在 \xcoord 和 \ycoord 中總是返回 1,儘管在 Tikz 圖片中使用時顯示實際因子。

關於如何修復有什麼想法嗎?

%!TeX program = lualatex
\documentclass[12pt]{article}

\usepackage{tikz}
\usetikzlibrary{math, calc}

%% https://tex.stackexchange.com/questions/86897/recover-scaling-factor-in-tikz
\newcommand*\getscale[1]{%
\begingroup
\pgfgettransformentries{\scaleA}{\scaleB}{\scaleC}{\scaleD}{\whatevs}{\whatevs}%
\pgfmathsetmacro{#1}{sqrt(abs(\scaleA*\scaleD-\scaleB*\scaleC))}%
\expandafter
\endgroup
\expandafter\def\expandafter#1\expandafter{#1}%
}

% for printing out coordinates in Tikz coordinate variable
\makeatletter
\newcommand\xcoord[1]{{%
    \getscale{\@scalefactor}%
    \pgfpointanchor{#1}{center}%
    \pgfmathparse{\pgf@x/\pgf@xx/\@scalefactor}%
    \pgfmathprintnumber{\pgfmathresult}%    
}}
\newcommand\ycoord[1]{{%
        \getscale{\@scalefactor}%
        \pgfpointanchor{#1}{center}%
        \pgfmathparse{\pgf@y/\pgf@yy/\@scalefactor}%
        \pgfmathprintnumber{\pgfmathresult}%
}}
\makeatother

\begin{document}

\begin{figure}
    \centering
    
    \begin{tikzpicture}[scale=1/10]
        % GRID - X
        \foreach \i in {0,24,...,120}{
            \draw[gray, thin] (\i,-12) -- (\i,184);
            \tikzmath{int \value; \value = \i;}; 
            \node[gray, below] at (\i,-12) {\value};
        }
        
        % GRID - Y
        \foreach \i in {0,24,...,168}{
            \draw[gray, thin] (-12,\i) -- (132,\i);
            \tikzmath{int \value; \value = \i;};
            \node[gray, left] at (-12,\i) {\value};
        }
    
        % Draw some lines with relative coordinates
        \draw[thick] (0,0) -- ++(12,0) coordinate (c);
        \draw[thick] (0,0) -- ++(0,60) coordinate (c);
        \draw[thick] (c) -- ++(0,36) coordinate (c);
        \draw[thick] (c) -- ++(0,76) coordinate (c);
        \draw[thick] (c) -- ++(120,0) coordinate (c);
        
        % Display coordinate
        \getscale{\scalefactor};
        \node[fill=white, text=blue] at (60,60) {Scale = \scalefactor};
        \node[fill=white, text=magenta, yshift=-15pt] at (c) {(\xcoord{c}, \ycoord{c})};            
    \end{tikzpicture}
\end{figure}
\end{document}

上面的程式碼可以編譯,但是洋紅色的座標與黑線的終點 (120, 172) 不符。

在此輸入影像描述

答案1

這是手動標記抽動的問題:您正在「計算」x 標籤,\tikzmath{int \value; \value = \i;};但這對縮放一無所知,因為這些只是數字,沒有「tikz 座標」。

解決方案是手動進行縮放,例如,透過

\tikzmath{int \value; \value = \i * \scalefactor;}; 

您可能必須考慮使用\value整數會帶來一些舍入錯誤,但這是另一個問題。

答案2

取得原始的、未變換的座標的方法可以在這裡找到存取 TikZ 座標的邏輯值

使用自訂命令

\makeatletter
\def\extractcoord#1#2#3{
  \path let \p1=(#3) in \pgfextra{
    \pgfmathsetmacro#1{\x{1}/\pgf@xx}
    \pgfmathsetmacro#2{\y{1}/\pgf@yy}
    \xdef#1{#1} \xdef#2{#2}
  };
}
\makeatother

可以像這樣顯示座標

\coordinate (A) at (120,172);
\extractcoord{\x}{\y}{A};
\node at (A) {Coordinates: \x, \y};

這是透過縮放、x 和 y 中的單位變更以及範圍環境進行測試的。

相關內容