如何定位节点?

如何定位节点?

我得到以下内容:

\documentclass{article}

\usepackage[latin1]{inputenc}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows}
\begin{document}
\pagestyle{empty}


% Define block styles
\tikzstyle{block} = [rectangle, draw, text width=5em, text centered,
  minimum height=4em]

\begin{tikzpicture}[node distance = 2cm, auto]
  % Place nodes
  \node [block] (I/O) {I/O};
  \node [block, below of = I/O] (CPU1) {CPU};
  \node [block, right of = CPU1] (CPU2) {CPU};
  \node [block, below of = CPU1] (Mem) {Memory};

  \draw [--] (I/O) -- (CPU1);
  \draw [--] (I/O) -| (CPU2);
  \draw [--] (CPU1) -- (Mem);
  \draw [--] (CPU2) |- (Mem);
\end{tikzpicture}


\end{document}

由此得出

在此处输入图片描述

如何将中心 CPU 节点 (CPU1) 移到左侧并复制 CPU2?抱歉,如果这还不够清楚,基本上只需移动中间节点,使右边缘与 I/O 和内存的左边缘对齐即可。

答案1

calc我认为如果您使用该库并稍微改变定位命令会更容易。

顺便说一句,我建议您使用简单的引用来命名节点,因为输入I/O一段时间后会变得乏味。使用小写字母,避免使用多余的符号,只使用字母和/或数字。

输出

示例图片

代码

\documentclass[margin=10pt]{standalone}   
\usepackage[latin1]{inputenc}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows,positioning,calc}
\begin{document}
\pagestyle{empty}


% Define block styles
\tikzstyle{block} = [rectangle, draw, text width=5em, text centered,
  minimum height=4em]

\begin{tikzpicture}%[node distance = 2cm, auto]
  % Place nodes
    \node [block] (io) {I/O};
    \node [block, below =2cm of io] (mem) {Memory};
    \node [block, anchor=east] (CPU1) at ($(io.south west)!.5!(mem.north west)$) {CPU};
    \node [block, anchor=west] (CPU2) at ($(io.south east)!.5!(mem.north east)$) {CPU}; 

    \draw (io) -| (CPU1);
    \draw (io) -| (CPU2);
    \draw (CPU1) |- (mem);
    \draw (CPU2) |- (mem);

\end{tikzpicture}
\end{document}

答案2

这是一个使用以下方法的解决方案:

  • positioningTikZ 库(新的和更好的语法left=of ...:)
  • node distance具有两种长度(使用曼哈顿距离)
  • on grid将节点相对于其中心进行定位的选项
  • \tikszet代替\tikzstyle

在此处输入图片描述

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}[node distance = 2cm and 2cm,on grid]
  % Define block styles
  \tikzset{
    block/.style={
      rectangle, draw,
      text width=5em, text centered,
      minimum height=4em,
    }
  }

  % Place nodes
  \node [block] (I/O) {I/O};
  \node [block, below left= of I/O] (CPU1) {CPU};
  \node [block, below right= of I/O] (CPU2) {CPU};
  \node [block, below right= of CPU1] (Mem) {Memory};

  \draw (I/O) -| (CPU1);
  \draw (I/O) -| (CPU2);
  \draw (CPU1) |- (Mem);
  \draw (CPU2) |- (Mem);
\end{tikzpicture}
\end{document}

相关内容