我有一个节点,我想填充一个12pt
垂直距离和6pt
水平距离都较大的矩形。我知道这是可行的
\documentclass[10pt,convert={convertexe=magick,density=1000,outext=.png}]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node[draw,rectangle] (a) at (0,0) {test};
\path (a.south west) +(-6pt,-3pt) coordinate (b);
\path (a.north east) +(6pt,3pt) coordinate (c);
\fill[opacity=0.3] (b) rectangle (c);
\end{tikzpicture}
\end{document}
但是,这种方法效率很低,因为我必须定义两个额外的坐标。有没有更简单的方法来实现相同的结果,因为这种情况在我的文档中重复多次,并且形状、大小等都不同?
答案1
如果您使用,则无需定义坐标shift
,例如([shift={(6pt, -3pt)}]a.south east)
。另一个选择是使用fit
库并分别设置inner xsep
和inner ysep
,请参阅下面的代码示例。
\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}
\node[draw,rectangle] (a) at (0,0) {test};
% your method
\path (a.south west) +(-6pt,-3pt) coordinate (b);
\path (a.north east) +(6pt,3pt) coordinate (c);
\fill[opacity=0.3] (b) rectangle (c);
% using shift
\fill [blue, opacity=0.3] ([shift={(-6pt, 3pt)}]a.north west) rectangle ([shift={(6pt, -3pt)}]a.south east);
% fit node
\node [inner xsep=6pt, inner ysep=3pt, fill=red, opacity=0.3, fit=(a)] {};
\end{tikzpicture}
\end{document}
答案2
对于节点或更复杂的图片,另一种有效的方法是使用background rectangle
。您不必担心坐标,TiKZ
它会为您完成。
\documentclass[tikz]{standalone}
\usetikzlibrary{backgrounds}
\begin{document}
\begin{tikzpicture}[%
background rectangle/.style={fill=gray!50},
inner frame xsep=6pt,
inner frame ysep=3pt},
show background rectangle]
\node[draw] {Test};
\end{tikzpicture}
\begin{tikzpicture}[%
background rectangle/.style={fill=gray!50},
inner frame xsep=6pt,
inner frame ysep=3pt,
show background rectangle]
\node[draw] (A) {Test};
\node[draw, circle] (B) at (1,0) {Test};
\end{tikzpicture}
\end{document}