我是 tikz 的新手,正在尝试理解该\foreach
函数。这是我的代码:
\documentclass[border=10pt]{standalone}
\usepackage{tikz}\usetikzlibrary{calc,shapes,positioning,arrows,positioning,shapes.geometric,fit,trees}
\begin{document}
\tikzstyle{block} = [diamond, draw, text width=6em, text badly centered, node distance=3cm, inner sep=0pt]
\begin{tikzpicture}[subs/.style={grow=down,xshift=1em,anchor=west,edge from parent path={(\tikzparentnode.south) |- (\tikzchildnode.west)}},
blk/.style={rectangle,draw},
first/.style={level distance=6ex},second/.style={level distance=12ex},third/.style={level distance=18ex},
fourth/.style={level distance=24ex},fifth/.style={level distance=30ex},sixth/.style={level distance=36ex},
seventh/.style={level distance=42ex},eigth/.style={level distance=48ex},ninth/.style={level distance=54ex},
level 1/.style={sibling distance=20em}]
%UAS
\coordinate
node[blk]{UAS}
[edge from parent fork down]
%UAV
child{node[blk] {UAV}
child[subs,first] {node[blk]{Power}}
child[subs,second] {node[blk]{Flight computer}}
child[subs,third] {node[blk] {Landing gear}}
child[subs,fourth]{node[blk]{Flight controls}}
child[subs,fifth]{node[blk]{Airframe}}
child[subs,sixth]{node[blk]{Engine (propulsion/fuel)}}
child[subs,seventh]{node[blk]{Communication/navigation}}
child[subs,eigth]{node[blk]{Electrical/hydraulics/environmental}}
child[subs,ninth]{node[blk]{Environmental control}}
}
\end{tikzpicture}
\end{document}
如您所见,我创建了九种样式来移动页面上的每个子项。这似乎非常不切实际且笨重。我曾考虑使用该\foreach
功能根据子项数量自动执行此移动过程,但无法正常工作。有人能帮忙吗?
答案1
嗯,这比想象的要困难。我想我做到了……
完整代码:
\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc,shapes,positioning,arrows,positioning,shapes.geometric,fit,trees}
\begin{document}
\tikzstyle{block} = [diamond, draw, text width=6em, text badly centered, node distance=3cm, inner sep=0pt]
\begin{tikzpicture}[%
subs/.style={grow=down,xshift=1em,anchor=west,edge from parent path={(\tikzparentnode.south) |- (\tikzchildnode.west)}},
blk/.style={rectangle,draw},
level 1/.style={sibling distance=20em}
]
\coordinate
node[blk]{UAS}
[edge from parent fork down]
child { node[blk] {UAV}
child [subs,style={level distance=6 ex}]
foreach [count=\i,
evaluate={\j=6*(\i-1);}] \p in
{Power,computer,Landing gear,Flight controls,Airframe,Engine (propulsion/fuel),Communication/navigation,Electrical/hydraulics/environmental,Environmental control}
{child[subs,style={level distance=\j ex}] {node[blk]{\p}}}
};
\end{tikzpicture}
\end{document}
结果: