![使用 pgfmathanglebetweenlines 新手问题](https://linux22.com/image/348399/%E4%BD%BF%E7%94%A8%20pgfmathanglebetweenlines%20%E6%96%B0%E6%89%8B%E9%97%AE%E9%A2%98.png)
我刚开始使用 tikz,我想使用\pgfmathanglebetweenlines
,但我显然不理解它。我期望以下代码报告参数中的角度,但它每次\try
都显示为 0 o (有时每次为 45 o或每次为 90 o)。我做错了什么?
%
% preamble
%
\documentclass[10pt]{article}
\usepackage{amssymb,amsmath}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{tikz}
\usetikzlibrary{calc,intersections}
%
% drawing.
%
\begin{document}
\def\try#1{
\begin{tikzpicture}[scale=4]
\coordinate[label=below:$O$](O)at(0,0);
\coordinate[label=$X$](X)at(1,0);
\coordinate[label=$Y$](Y)at({cos(#1)},{sin(#1)});
\draw(Y)--(O)--(X);
\pgfmathanglebetweenlines{(O)}{(Y)}{(O)}{(X)}
\coordinate[label=right:{$\angle YOX=\pgfmathresult^\circ$}](label)at(X);
\end{tikzpicture}
\\}
\try{20}\try{45}\try{60}\try{180}\try{405}\try{-45}
\end{document}
答案1
这里有几个问题。首先,\pgfmathanglebetweenlines
需要基本的图层坐标规范(例如,在本例中\pgfpointanchor{Y}{center}
)。其次,\pgfmathresult
每次使用数学引擎时都会重新定义,因此在排版时角度测量就会丢失。
解决方案如下所示。请注意,我还添加了对锐角的修正(我认为文档\pgfmathanglebetweenlines
不太正确),并将角度四舍五入为最接近的整数。
\documentclass[varwidth,border=5]{standalone}
\usepackage{tikz}
\def\try#1{%
\begin{tikzpicture}[scale=4]
\coordinate[label=below:$O$] (O) at (0,0);
\coordinate[label=$X$] (X) at (1,0);
\coordinate[label=$Y$] (Y) at (cos #1, sin #1);
\draw (Y) -- (O) -- (X);
\pgfmathanglebetweenlines%
{\pgfpointanchor{O}{center}}{\pgfpointanchor{Y}{center}}
{\pgfpointanchor{O}{center}}{\pgfpointanchor{X}{center}}
\pgfmathparse{int(round(min(\pgfmathresult, 360-\pgfmathresult))}% Correction
\let\angleyox=\pgfmathresult
\coordinate [label=right:{$\angle YOX=\angleyox^\circ$}] (label) at (X);
\end{tikzpicture}
\\}
\begin{document}
\foreach \a in {20, 45, 60, 180, 405,-45}{\try{\a}}
\end{document}
但是!基本层的东西不是必需的。该calc
库提供了您需要的所有内容:
\documentclass[varwidth,border=5]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\def\try#1{%
\begin{tikzpicture}[scale=4]
\coordinate[label=below:$O$] (O) at (0,0);
\coordinate[label=$X$] (X) at (1,0);
\coordinate[label=$Y$] (Y) at (cos #1, sin #1);
\draw (Y) -- (O) -- (X);
\path let \p1=(O),\p2=(Y),\p3=(X),
\n1={atan2(\y2-\y1,\x2-\x1)},
\n2={atan2(\y3-\y1,\x3-\x1)} in
node at (X) [right] {\pgfmathparse{int(abs(\n2-\n1))}% Correction
$\angle YOX=\pgfmathresult^\circ$};
\end{tikzpicture}
\\}
\begin{document}
\foreach \a in {20, 45, 60, 180, 405,-45}{\try{\a}}
\end{document}