![tikz节点将文本对齐到矩形底部](https://linux22.com/image/252497/tikz%E8%8A%82%E7%82%B9%E5%B0%86%E6%96%87%E6%9C%AC%E5%AF%B9%E9%BD%90%E5%88%B0%E7%9F%A9%E5%BD%A2%E5%BA%95%E9%83%A8.png)
如何在没有硬编码值的情况下将节点的文本与矩形底部对齐?(水平居中但底部对齐)
\tikz[]{
\node[shape=rectangle, inner sep=8pt, minimum height=1.2cm, fill=black, text=white, font=\huge, text depth=-0.6cm] {test};
}\tikz[]{
\node[shape=rectangle, inner sep=8pt, minimum height=1.2cm, fill=black, text=white, font=\huge, text depth=0cm] {test};
}\tikz[]{
\node[shape=rectangle, inner sep=8pt, minimum height=1.2cm, fill=black, text=white, text depth=-0.6cm] {test};
}\tikz[]{
\node[shape=rectangle, inner sep=8pt, minimum height=1.2cm, fill=black, text=white, text depth=0cm] {test};
}
显然text depth
可以硬编码,但我希望它能够自动适用于任何给定的字体和矩形高度。
答案1
如果文本大小小于最小高度,您可以尝试text height
使用minimum height
:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\tikz[]{
\node[shape=rectangle, inner sep=0pt, fill=black, text=white,
font=\huge, text height=1.2cm] {test};
}
\tikz[]{
\node[shape=rectangle, inner sep=0pt, fill=black, text=white,
font=\huge, text height=1.2cm] {test yjp};
}
\tikz[]{
\node[shape=rectangle, inner sep=0pt, fill=black, text=white,
font=\huge, text height=1.2cm,text depth=0cm] {test yjp};
}
\end{document}
答案2
可能: \parbox
这个宏采用可选参数来设置框的高度。
\documentclass{article}
\usepackage{tikz}
\begin{document}
\tikz \node[shape = rectangle,
inner sep = 0pt, draw,
fill = black,
text = white,
minimum height = 2cm,
minimum width = 4cm] {\parbox[b][2cm]{4cm}{Simple \huge{test}}};
\end{document}
答案3
您可以创建一个给定高度的垂直框,并将文本放在该框的底部。这可以使用以下宏来完成:
\def\bottom#1#2{\hbox{\vbox to #1{\vfill\hbox{#2}}}}
您可以在 TikZ 节点内使用上述宏。“不好”的部分是您必须给出该框的所需高度,并且您必须考虑inner sep
(将添加到给定高度)和minimum height
(必须大于或等于,最好等于给定高度加上两个内部 sep 的总和)。
我希望以下 MWE 可以更清楚地表达我的意思:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\def\bottom#1#2{\hbox{\vbox to #1{\vfill\hbox{#2}}}}
\tikz[]{
\node[shape=rectangle, inner sep=1mm, minimum height=1.2cm, fill=black, text=white, font=\huge] {test};
}\tikz[]{
\node[shape=rectangle, inner sep=1mm, minimum height=1.2cm, fill=black, text=white, font=\huge] {\bottom{1cm}{test}};
}\tikz[]{
\node[shape=rectangle, inner sep=1mm, minimum height=1.2cm, fill=black, text=white] {test};
}\tikz[]{
\node[shape=rectangle, inner sep=1mm, minimum height=1.2cm, fill=black, text=white] {\bottom{1cm}{test}};
}
\end{document}
结果如下: