所以我想填充一个矩形,像下面这样,但不需要循环和获取坐标的麻烦。
我想要一个神奇的命令,将我的符号重复放置在矩形内。最好给出开始和结束coordinate
;
\automagicGrid[step size x=0.1, step size y=0.1]{(rect.south west)}{(rect.north east)}{\node{$\otimes$}}
这是一个手动的、糟糕的操作方法的例子。
\documentclass[margin=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}
\makeatletter
\tikzset{autofit/.style={
% autofit: automagically generate awesome anchorpoints
fit={(\pgf@pathminx,\pgf@pathminy) (\pgf@pathmaxx,\pgf@pathmaxy)},
inner sep=0pt
}
}
\makeatother
% Draw my rectangle
\def\rectH{2}
\def\rectW{2}
\draw(0,0) rectangle (\rectW,\rectH) node[autofit](rect){};
% I want this command
% \automagicGrid[step size x=0.1, step size y=0.1]{(rect.south west)}{(rect.north east)}{\node{$\otimes$}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Below is what I DON'T want %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\def\xStart{.2}
\def\xStepSize{.3}
\edef\paddingX{.1}
\pgfmathsetmacro\xStep{\xStart+\xStepSize}
\pgfmathsetmacro\xEnd{\rectH-\paddingX}
\def\yStart{.2}
\def\yStepSize{.3}
\edef\paddingY{.1}
\pgfmathsetmacro\yStep{\yStart+\xStepSize}
\pgfmathsetmacro\yEnd{\rectH-\paddingY}
\foreach \x in {\xStart,\xStep,...,\xEnd}{
\foreach \y in {\yStart, \yStep,...,\yEnd}{
\node at (\x+\paddingX/2,\y+\paddingY/2){$\otimes$};
}
}
\end{tikzpicture}
\end{document}
结果如下:
不过,如果有人能找到一种干净的方法来获取所述坐标,我会很高兴,因为这才是真正的麻烦。
答案1
我不知道如何去掉,\foreach
但可以将它们放入样式中。使用我们path picture
现在知道要填充的东西有多大,并且可以相应地拨动循环参数。
\documentclass[margin=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{fit,calc}
\pgfkeys{/automagic/.cd,
grid/.style={draw=gray!50,thin},
x distance/.initial=3mm,
y distance/.initial=3mm,
x padding/.initial=2.5mm,
y padding/.initial=2.5mm,
distance/.code={\pgfkeys{/automagic/x distance=#1,/automagic/y distance=#1}},
symbol/.initial= $\otimes$
}
\tikzset{automagic grid/.style={/utils/exec=\pgfkeys{/automagic/.cd,#1},
path picture={
\path[/automagic/grid]
let
\p1=($(path picture bounding box.north east)-(path picture bounding box.south west)$),
\n1={int(0.5+(\x1-\pgfkeysvalueof{/automagic/x padding})/\pgfkeysvalueof{/automagic/x distance})},
\n2={int(0.5+(\y1-\pgfkeysvalueof{/automagic/y padding})/\pgfkeysvalueof{/automagic/y distance})}
in
foreach \XX in {1,...,\n1}
{
foreach \YY in {1,...,\n2} {
([
xshift={(\XX-1)*\pgfkeysvalueof{/automagic/x distance}+\pgfkeysvalueof{/automagic/x padding}},
yshift={(\YY-1)*\pgfkeysvalueof{/automagic/y distance}+\pgfkeysvalueof{/automagic/y padding}}
]%
path picture bounding box.south west%
) node{\pgfkeysvalueof{/automagic/symbol}}
}
};
}}}
\begin{document}
\begin{tikzpicture}
% Draw my rectangle
\def\rectH{2}
\def\rectW{2}
\draw[automagic grid](0,0) rectangle ++(\rectW,\rectH);
\end{tikzpicture}
\end{document}