我的文档中有很多tikzpicture
元素。我希望所有元素自动居中,而无需写入\begin{center}...\end{center}
。我找到了一个解决方案通过以下代码使图形居中:
\documentclass{memoir}
\usepackage[draft]{graphicx}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
% Solution 1 <--- Best for figures
\setfloatadjustment{figure}{\centering}
% Solution 2 <--- does not work
% \makeatletter
% \g@addto@macro\@floatboxreset{\centering}
% \makeatother
% % Solution 3 --- works
% \let\origfigure\figure
% \let\endorigfigure\endfigure
% \renewenvironment{figure}[1][tbph]{%
% \origfigure[#1]%
% \centering
% }{%
% \endorigfigure
% }
\begin{document}
The first paragraph.
\begin{figure}
\includegraphics{a.jpg}
\caption[Long caption]{Caption}
\label{pic-a}
\end{figure}
And the second.
\begin{tikzpicture}
\node[rectangle,
draw = blue,
text = olive,
fill = gray!30,
minimum width = 5cm,
minimum height = 1cm] (r) at (0,0) {Rectangle};
\end{tikzpicture}
\begin{tikzpicture}
\node[isosceles triangle,
draw,
fill=cyan!30,
minimum size =3cm] (T) at (0,0) {};
\end{tikzpicture}
\end{document}
但是,我的tikzpicture
元素没有受到影响。我该怎么做(将所有 tikzpictures 设置为自动居中,而无需\begin{center}...\end{center}
每次都使用?
答案1
你可能不想每一个 tikzpicture
居中。一种选择是创建一个新环境:
\documentclass{memoir}
\usepackage{tikz}
\newenvironment{centikz}{\begin{center}\begin{tikzpicture}}{\end{tikzpicture}\end{center}}
\begin{document}
An inline tikzpicture \begin{tikzpicture}\draw(0,0) node[fill, inner sep=3pt]{} to (1,0) node[fill, inner sep=3pt]{};\end{tikzpicture}
should not be centered, using either begin/end notation or \tikz{\draw(0,0) node[fill, inner sep=3pt]{} to (1,0) node[fill, inner sep=3pt]{};} shortened notation.
But sometimes \begin{centikz}\draw(0,0) node[fill, inner sep=3pt]{} to (1,0) node[fill, inner sep=3pt]{};\end{centikz}
you want it that way.
\end{document}
答案2
您可以tikzpicture
使用以下方式集中所有环境
\documentclass{memoir}
\usepackage{etoolbox}
\usepackage{tikz}
\BeforeBeginEnvironment{tikzpicture}{\begin{center}}
\AfterEndEnvironment{tikzpicture}{\end{center}}
\begin{document}
\begin{tikzpicture}
\node {Test};
\end{tikzpicture}
\end{document}
这里
\BeforeBeginEnvironment{environment}{code before}
和
\AfterEndEnivronment{environment}{code after}
前置和后置code before
以及code after
到\begin{environment}
和\end{environment}
。请参阅etoolbox 文档更多细节。
请注意,如果您正在使用memoir
或更新版本的 LaTeX,则可能不需要该etoolbox
包即可工作。