TIKZ:foreach 与 calc-library 不兼容?

TIKZ:foreach 与 calc-library 不兼容?

我想在一组点之间画一组线,并在每条线的 1/3 和 2/3 点上画一条垂直线。为了做到这一点,我首先定义了点,然后想使用循环来绘制\foreach。然而,foreach 循环似乎不适用于calc

以下代码描述了我想要做的事情。问题是 for 循环中的表达式($0.333*\x + 0.666*\y$)似乎确实会导致问题。(例如,虽然 ($0.333*(A) + 0.666*(B)$)有效。)有人能告诉我我做错了什么/我需要改变什么才能使它工作吗?

\documentclass{article} 
\usepackage{tikz}
\usepackage{pgfplots} 
\usetikzlibrary{patterns}
\usetikzlibrary{calc}
\usetikzlibrary{arrows.meta}
\usepackage{ifthen}
\begin{document}

\begin{center}
\begin{tikzpicture}
\coordinate (A) at (-3,1);
\coordinate (B) at (3,3);
\coordinate (C) at (0,3);
\foreach \x/\y in {(A)/(B),(B)/(C),(A)/(C)}{
\draw[-] \x -- \y; 
\draw[dashed] ($0.333*\x + 0.666*\y$) -- +(0,1);
\draw[dashed] ($0.666*\x + 0.333*\y$) -- +(0,1);
}
\end{tikzpicture}
\end{center}
\end{document}

答案1

TikZ 库表达式里面需要用到括号作为语法字符,calc但坐标名称可以放入宏中:

\coordinate (A) at (-3,1);
\coordinate (B) at (3,3);
\coordinate (C) at (0,3);
\foreach \x/\y in {A/B,B/C,A/C}{
  \draw[-] (\x) -- (\y);
  \draw[dashed] ($0.333*(\x) + 0.666*(\y)$) -- +(0,1);
  \draw[dashed] ($0.666*(\x) + 0.333*(\y)$) -- +(0,1);
}

完整示例:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{patterns}
\usetikzlibrary{calc}
\begin{document}

\begin{center}
  \begin{tikzpicture}
    \coordinate (A) at (-3,1);
    \coordinate (B) at (3,3);
    \coordinate (C) at (0,3);
    \foreach \x/\y in {A/B,B/C,A/C}{
      \draw[-] (\x) -- (\y);
      \draw[dashed] ($0.333*(\x) + 0.666*(\y)$) -- +(0,1);
      \draw[dashed] ($0.666*(\x) + 0.333*(\y)$) -- +(0,1);
    }
  \end{tikzpicture}
\end{center}
\end{document}

结果

答案2

您必须先扩展\x\y才能将它们提供给 calc 库。有两种方法,请参见示例。

\documentclass{article}
\pagestyle{empty}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}

\begin{tikzpicture}
  \coordinate (A) at (-3,1);
  \coordinate (B) at (3,3);
  \coordinate (C) at (0,3);
  \foreach \x/\y in {(A)/(B),(B)/(C),(A)/(C)}{
    \draw[-] \x -- \y;

    % (1) expand only the point
    \edef\p{($0.333*\x + 0.666*\y$)}
    \draw[dashed] \p -- +(0,1);

    % (2) expand the whole path, protecting everything not to be
    % expanded by \noexpand
    \edef\a{\noexpand\draw[dashed] ($0.666*\x + 0.333*\y$) -- +(0,1);}\a
  }
\end{tikzpicture}

\end{document}

在此处输入图片描述

相关内容