答案1
这是一个简单的(?)代码,用于计算距离并将其存储在变量中。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\makeatletter
\newcommand{\Distance}[3]{% % from https://tex.stackexchange.com/q/56353/121799
\tikz@scan@one@point\pgfutil@firstofone($#1-#2$)\relax
\pgfmathsetmacro{#3}{round(0.99626*veclen(\the\pgf@x,\the\pgf@y)/0.0283465)/1000}
}% Explanation: the calc library allows us, among other things, to add and
% subtract points, so ($#1-#2$) is simply the difference between the points
% #1 and #2. The combination \tikz@scan@one@point\pgfutil@firstofone extracts
% the coordinates of the new point and stores them in \pgf@x and \pgf@y.
% They get fed in veclen, and \pgfmathsetmacro stores the result in #3.
% EDIT: included fudge factor, see https://tex.stackexchange.com/a/22702/121799
\makeatother
\begin{document}
\begin{tikzpicture}
\coordinate (X) at (1,0);
\coordinate (Y) at (3,0);
\draw[-] (X) -- (Y);
\node at (0,2) {\Distance{(X)}{(Y)}{\mylen}\mylen};
\end{tikzpicture}
\end{document}
答案2
可以使用以下方法手动计算sqrt(x^2 + y^2)
或veclen
按建议使用:
\documentclass{article}
\usepackage{tikz}
\begin{document}
% Euclidian distance from (3, 4) to (12, 5)
\pgfmathparse{sqrt((12 - 3)^2 + (5 - 4)^2)}\pgfmathresult
% Euclidian distance from (3, 4) to (12, 5)
\pgfmathparse{veclen(12 - 3, 5 - 4)}\pgfmathresult
\end{document}
存在舍入差异。
答案3
对于某些特殊情况,您也可以使用fit
节点。这样就无需存储距离值。
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{positioning, fit}
\begin{document}
\begin{tikzpicture}
\draw[fill=black] circle (1pt) node[below]{(0,0)} -- node[above]{4} ++(4,0) circle (1pt) node[below] {(4,0)};
\node[fit={(0,0) (4,0)}, inner xsep=0pt, draw, minimum height=1cm, anchor=south west] at (0,5mm) (a) {};
\end{tikzpicture}
\end{document}