如何在 tikzpicture 中放置內容?

如何在 tikzpicture 中放置內容?

我正在開發一個系統,我想在其中繪製一個矩形並建立該矩形的內容。我正在使用 tikz 繪製一個虛線矩形,但我很難將內容定位在繪製的矩形內。這是我遇到的問題的一個最小示例:

\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}
        \draw[dashed] (0, 0) rectangle node{this text is centered but I want it at the top left} (4.4in, 2.25in);
    \end{tikzpicture}

    \vspace{1cm}

    \begin{tikzpicture}
        \draw[dashed] (0, 0) rectangle (4.4in, 2.25in);
        \node at (0,0) {this text is centered at the bottom left and not fully in the container};
    \end{tikzpicture}

    \begin{tikzpicture}
        \draw[dashed] (0, 0) rectangle (4.4in, 2.25in);
        \node at (4,5.5) {this text is where I want it, but this is brute force};
    \end{tikzpicture}
\end{document}

生成這個:

範例輸出

有沒有一種方法可以讓我始終將內容定位在框架的左上角,而不必強制座標?我沒有在文檔中看到任何關於此的內容。如果有更好的方法,我願意接受不使用 TikZ 的解決方案。如果重要的話,我放入這些矩形中的實際內容要複雜得多。值得注意的是,這不是一張圖片。

答案1

我不知道我是否正確理解了你的問題。

我的理解是:在矩形中,如果將節點寫在座標之間,則節點始終放置在矩形的中心(座標的中間)。要將其放置在左上角頂點旁邊,該頂點只需是第一個座標即可。

\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}
        \draw[dashed] (0, 2.25in)  node[anchor=north west]{this text is centered but I want it at the top left}rectangle (4.4in, 0);
    \end{tikzpicture}

\end{document}

在此輸入影像描述

答案2

如果您想要多行文字。請注意,文字區域為 2.25 英寸 x 4.4 英寸,但虛線框稍大(邊界框為 0.666em + 0.8pt)。

\documentclass{article}
\usepackage{tikz}
\usepackage{blindtext}% radnom text

\begin{document}
    \begin{tikzpicture}[outline/.style={draw=black,dashed}]
        \node[outline]{\parbox[c][2.35in][t]{4.4in}{\blindtext}};
    \end{tikzpicture}

\end{document}

相關內容