我想用一条粗水平线连接我的圆柱体,如下图所示:
以下代码对于第一次连接运行良好:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes,intersections}
\begin{document}
\begin{tikzpicture}
\tikzstyle{mass} = [draw, fill=gray!20, cylinder, shape aspect=1, minimum width=1.5cm, minimum height=1cm, shape border rotate=180];
\foreach \xpos/\name/\tag in {0/J1/J_1, 2/J2/J_2, 4/J3/J_3, 6/J4/\cdots, 8/J5/J_n}
{
\node[mass, name=\name] at (\xpos cm,0cm) {};
\draw[shift=(\name.center)] node[] {$\tag$};
}
\path[name path=line1] (J2.before top) -- (J2.after top);
\path[name path=line2] (J2.top) -- (J2.bottom);
\draw[name intersections={of=line1 and line2}, thick] (J1.east) -- (intersection-1);
\end{tikzpicture}
出于显而易见的原因,我想使用\foreach
循环建立连接。我尝试了以下方法:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes,intersections}
\begin{document}
\begin{tikzpicture}
\tikzstyle{mass} = [draw, fill=gray!20, cylinder, shape aspect=1, minimum width=1.5cm, minimum height=1cm, shape border rotate=180];
\foreach \xpos/\name/\tag in {0/J1/J_1, 2/J2/J_2, 4/J3/J_3, 6/J4/\cdots, 8/J5/J_n}
{
\node[mass, name=\name] at (\xpos cm,0cm) {};
\draw[shift=(\name.center)] node[] {$\tag$};
}
\foreach \name1/\name2 in {J1/J2, J2/J3, J3/J4, J4/J5}
{
\path[name path=line1] (\name2.before top) -- (\name2.after top);
\path[name path=line2] (\name2.top) -- (\name2.bottom);
\draw[name intersections={of=line1 and line2}, thick] (\name1.east) -- (intersection-1);
}
\end{tikzpicture}
不幸的是,在第二个示例中,第二个\foreach
循环不起作用。LaTeX\inaccessible
在编译期间会抛出错误。似乎我无法\foreach
像之前那样在第二个循环中访问节点名称?
答案1
在控制序列中不能将数字和字母一起使用。
控制序列名称可以是单个非字母,也可以是一个或多个字母的序列。
因此,\name1
在这种情况下以及一般情况下,这是一个非法名称;在某些情况下它似乎有效,但不要指望这一点。
使用
\foreach \namea/\nameb in {J1/J2, J2/J3, J3/J4, J4/J5}
{
\path[name path=line1] (\nameb.before top) -- (\nameb.after top);
\path[name path=line2] (\nameb.top) -- (\nameb.bottom);
\draw[name intersections={of=line1 and line2}, thick] (\namea.east) -- (intersection-1);
}
路径或坐标名称中的数字是合法的,但原因完全不同。
答案2
由于 egreg 修正了您的代码,我通过使用单个变量的循环来简化它,因为其他两个可以由单个变量生成。
\documentclass[border=5mm,tikz]{standalone}
\usetikzlibrary{shapes,intersections}
\begin{document}
\begin{tikzpicture}
\tikzset{mass/.style={draw, fill=gray!20, cylinder, shape aspect=1, minimum width=1.5cm, minimum height=1cm, shape border rotate=180}}
\foreach \tag[count=\xpos from 0] in {J_1,J_2,J_3,\cdots,J_n}
{
\node[mass, name=J\xpos] at (2*\xpos,0) {};
\draw[shift=(J\xpos.center)] node[] {$\tag$};
}
\foreach \n [evaluate=\n as \lastn using int(\n+1)] in {0,1,2,3}
{
\path[name path=line1] (J\lastn.before top) -- (J\lastn.after top);
\path[name path=line2] (J\lastn.top) -- (J\lastn.bottom);
\draw[name intersections={of=line1 and line2}, thick] (J\n.east) -- (intersection-1);
}
\end{tikzpicture}
\end{document}