在 tikz 中计算并在图形中间添加注释

在 tikz 中计算并在图形中间添加注释

我想计算几何图形的中心,并在该坐标上创建一个带有一些文本的节点。当我尝试做一些简单的正方形时,我得到了

! Package pgf Error: No shape named (0 is known.

我在 MikTeX 2.9.4248 上使用以下 MWE:

\documentclass[a4paper,10pt,fleqn]{article}
\usepackage{graphicx}
\usepackage{subfigure}
\usepackage{textcomp}
\usepackage{color}
\usepackage{hyperref}
\usepackage{tikz}
\usetikzlibrary{positioning}


%%% this draws a 6mm edged square provided the top-left coordinates are given
\newcommand*\squareNVSEN[3]{  
  \draw [draw=gray, very thin]
      ( #1 mm,  #2 mm)
   -| ( #1 mm + 6.00mm, #2 mm - 6.00mm)
   -| ( #1 mm,  #2 mm);

  \node at ( (#1 mm + 6.00mm)/2,  (#2 mm + 6.00mm)/2) {#3};
%%% I'm not sure how the formula is interpreted by pdfLaTeX
%%% for general coordinates: (x1+x2)/2 & (y1+y2)/2
%%% for coordinates and lengths: (2*x1+Length)/2 & (2*y1+height)/2
}


\begin{document}
\begin{figure}[tH]
  \begin{tikzpicture}[
    xscale=2,
    yscale=2,
    virtual/.style={thin,dashed}
    ]

    \squareNVSEN{0.0}{0.0}{A in the middle}
    \squareNVSEN{7.0}{7.0}{B in the middle}
  \end{tikzpicture}
  \caption{some text}
\end{figure}
\end{document}

谢谢你!

答案1

为了得到你想要的结果,你应该用括号括起 x 和 y 的计算。但正如 SebGlav 在评论中所建议的那样,可以使用库简化代码calc。Ti 使用的默认单位Z 是cm,即如果你写(1,1),这意味着(1cm,1cm)。

\documentclass[a4paper,10pt,fleqn]{article}
\usepackage{graphicx}
\usepackage{subfigure}
\usepackage{textcomp}
\usepackage{color}
\usepackage{hyperref}
\usepackage{tikz}
\usetikzlibrary{positioning}


%%% this draws a 6mm edged square provided the top-left coordinates are given
\newcommand*\squareNVSEN[3]{  
  \draw [draw=gray, very thin]
      ( #1 mm,  #2 mm)
   -| ( #1 mm + 6.00mm, #2 mm - 6.00mm)
   -| ( #1 mm,  #2 mm);

  \node at ( {(#1 mm + 6.00mm)/2},  {(#2 mm + 6.00mm)/2}) {#3};
%%% I'm not sure how the formula is interpreted by pdfLaTeX
%%% for general coordinates: (x1+x2)/2 & (y1+y2)/2
%%% for coordinates and lengths: (2*x1+Length)/2 & (2*y1+height)/2
}


\begin{document}
\begin{figure}[t]
  \begin{tikzpicture}[
    xscale=2,
    yscale=2,
    virtual/.style={thin,dashed}
    ]

    \squareNVSEN{0.0}{0.0}{A in the middle}
    \squareNVSEN{7.0}{7.0}{B in the middle}
  \end{tikzpicture}
  \caption{some text}
\end{figure}
\end{document}

在此处输入图片描述

答案2

你不必要地把简单的事情复杂化了。你想要的只是一个这样的命令:

\draw[draw=gray, very thin] (#1mm,#2mm) rectangle ++(-6mm,-6mm) node[pos=.5] {#3};

您可以在任何地方调用它。rectangle是一个基本的绘图对象,它支持node指定的pos设置。

\usepackage{tikz}
\usetikzlibrary{positioning}

\newcommand*\squareNVSEN[3]{
  \draw[draw=gray, very thin] (#1mm,#2mm) rectangle ++(-6mm,-6mm) node[pos=.5] {#3}; 
}

\begin{document}
\begin{figure}[!htbp]\centering
  \begin{tikzpicture}[
    xscale=2,
    yscale=2,
    virtual/.style={thin,dashed}
    ]
    \squareNVSEN{0.0}{0.0}{A in the middle}
    \squareNVSEN{7.0}{7.0}{B in the middle}
  \end{tikzpicture}
  \caption{some text}
\end{figure}
\end{document}

在此处输入图片描述

相关内容