如下图所示,TikZbackgruound
库允许创建具有自动宽度/高度设置的背景。
\usetikzlibrary{backgrounds}
\begin{tikzpicture}
[show background rectangle, background rectangle/.style={fill=magenta}]
\shade[ball color=blue] (0,0) circle (10ex);
\end{tikzpicture}
如果我们想定义宽度或指定 \textwidth、\columnwidth 等作为背景层的宽度,该怎么办?下图显示了所需结果的草图。
答案1
您可以定义一个名为 的新键auto centering
。此键添加一个空节点,该节点围绕 的内容tikzpicture
。minimum width
此节点的长度是作为参数给出的长度(默认值为\columnwidth
):
\usetikzlibrary{backgrounds,fit}
\makeatletter
\tikzset{
auto centering/.style={execute at end picture={
\node[fit=(current bounding box),minimum width=#1-2*\tikz@framexsep,inner sep=0,
]{};
}},
auto centering/.default=\columnwidth,
}
\makeatother
在您的文档中,添加此键作为第一的你的tikzpicture
s 选项。
以下是一个例子:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{backgrounds,fit}
\makeatletter
\tikzset{
auto centering/.style={execute at end picture={
\node[fit=(current bounding box),minimum width=#1-2*\tikz@framexsep,inner sep=0,
]{};
}},
auto centering/.default=\columnwidth,
}
\makeatother
\usepackage{multicol}
\usepackage{lipsum}
\begin{document}
\lipsum[4]
\noindent\begin{tikzpicture}
[auto centering,show background rectangle,background rectangle/.style={fill=magenta}]
\shade[ball color=blue] (0,0) circle (10ex);
\end{tikzpicture}
\begin{multicols}{2}
\lipsum[4]
\noindent\begin{tikzpicture}
[auto centering,show background rectangle, background rectangle/.style={fill=orange}]
\shade[ball color=blue] (0,0) circle (10ex);
\end{tikzpicture}
\noindent\begin{tikzpicture}
[auto centering,show background rectangle, background rectangle/.style={fill=lime}]
\shade[ball color=blue] (0,0) circle (10ex);
\end{tikzpicture}
\lipsum[4]
\end{multicols}
\end{document}
答案2
首先绘制中间的球体:
\shade[ball color=blue] (0.5\linewidth,0) circle (10ex); %% note 0.5\linewidth
为了增加背景的宽度\textwidth
,当你绘画时background rectangle
,画一些横跨文本宽度的东西就足够了,比如
\path(0,0) --(\linewidth,0);
这是一条贯穿的不可见线\linewidth
。另外添加inner frame xsep=0pt
到背景矩形中。
\documentclass{article}
\usepackage{tikz,showframe} %% showframe just for demo
\usetikzlibrary{backgrounds}
\begin{document}
\noindent
\begin{tikzpicture}%
[show background rectangle,inner frame xsep=0pt, background rectangle/.style={fill=magenta,line width=0pt}]
%% you can also use `tight background` instead of `inner frame xsep`.
\shade[ball color=blue] (0.5\linewidth,0) circle (10ex);
\path(0,0) --(\linewidth,0);
\end{tikzpicture}%
\end{document}
这是一个更简单的版本,其中背景首先绘制为一个矩形。
\documentclass{article}
\usepackage{tikz,showframe}
\begin{document}
\noindent
\begin{tikzpicture}%
\path[use as bounding box,line width=0pt,fill=magenta](-0.5\linewidth,-11ex) rectangle(0.5\linewidth,11ex);
\shade[ball color=blue] (0,0) circle (10ex);
\end{tikzpicture}%
\end{document}