我是 Tikz 的新手。请考虑以下最小示例:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw[very thick] (-2,-2) rectangle (2,2);
\draw (-2,-2) grid (2,2);
\fill (1,1) circle [radius=3pt];
\end{tikzpicture}
\begin{tikzpicture}[x=0.5cm,y=0.5cm]
\draw[very thick] (-2,-2) rectangle (2,2);
\draw (-2,-2) grid (2,2);
\fill (1,1) circle [radius=3pt];
\end{tikzpicture}
\end{document}
我遇到的问题是,在第二张图片中,网格没有考虑单位长度。我遗漏了什么?我应该怎么做才能让网格“知道”我已经更改了单位?
答案1
根据手册,网格是按照/tikz/step=h
手册中所述的配置步骤绘制a number or dimension or coordinate
的(no default, initially 1cm)
。
因此,如果您希望网格不以 1cm 为单位绘制,则必须更改step
,如(或本地,仅针对网格绘制命令):
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw[very thick] (-2,-2) rectangle (2,2);
\draw (-2,-2) grid (2,2);
\fill (1,1) circle [radius=3pt];
\end{tikzpicture}
\begin{tikzpicture}[x=0.5cm,y=0.5cm,step=0.5cm]
\draw[very thick] (-2,-2) rectangle (2,2);
\draw (-2,-2) grid (2,2);
\fill (1,1) circle [radius=3pt];
\end{tikzpicture}
\end{document}
答案2
xstep
网格分离由和控制,ystep
它们分别将值存储在\tikz@grid@x
和中\tikz@grid@y
。它们的初始值定义为tikz.code.tex
\def\tikz@grid@x{1cm}%
\def\tikz@grid@y{1cm}%
在您的第二个示例中,您设置了x=0.5cm, y=0.5cm
,这意味着(-2, -2)
被解析为(-1cm, -1cm)
并且(2, 2)
被解析为(1cm, 1cm)
。这是因为当将 coordinates 传递给 parse 时,首先检查 x 和 y 坐标是否以 为单位\tikz@checkunit
。然后 tikz 可以判断它是否以 为单位\iftikz@isdimension
,如果不是,则坐标设置为\pgfpointxy
,否则坐标设置为\pgfpoint
。实际上有四种情况需要处理,相关代码是
\def\tikz@@@parse@regular#1#2#3){%
\pgfutil@in@,{#3}%
\ifpgfutil@in@%
\tikz@parse@splitxyz{#1}{#2}#3,%
\else%
\tikz@checkunit{#2}%
\iftikz@isdimension%
\tikz@checkunit{#3}%
\iftikz@isdimension%
\def\pgfutil@next{#1{\pgfpoint{#2}{#3}}}%
\else%
\def\pgfutil@next{#1{\pgfpointadd{\pgfpoint{#2}{0pt}}{\pgfpointxy{0}{#3}}}}%
\fi%
\else%
\tikz@checkunit{#3}%
\iftikz@isdimension%
\def\pgfutil@next{#1{\pgfpointadd{\pgfpoint{0pt}{#3}}{\pgfpointxy{#2}{0}}}}%
\else%
\def\pgfutil@next{#1{\pgfpointxy{#2}{#3}}}%
\fi%
\fi%
\fi%
\pgfutil@next%
}%
类似的解析机制也适用xstep
于ystep
\tikz@checkunit{\tikz@grid@x}%
\iftikz@isdimension%
\pgf@process{\pgfpoint{\tikz@grid@x}{0pt}}%
\else%
\pgf@process{\pgfpointxy{\tikz@grid@x}{0}}%
\fi%
\pgf@xb=\pgf@x%
\pgf@yb=\pgf@y%
\tikz@checkunit{\tikz@grid@y}%
\iftikz@isdimension%
\pgf@process{\pgfpoint{0pt}{\tikz@grid@y}}%
\else%
\pgf@process{\pgfpointxy{0}{\tikz@grid@y}}%
\fi%
\advance\pgf@xb by\pgf@x%
\advance\pgf@yb by\pgf@y%
\pgfpathgrid[stepx=\pgf@xb,stepy=\pgf@yb]%
{\pgfqpoint{\pgf@xa}{\pgf@ya}}{\pgfqpoint{\tikz@lastx}{\tikz@lasty}}%
在您的示例中,它们只是1cm
,因此可以通过
\draw (-1cm, -1cm) grid (1cm, 1cm);
并且\fill (1, 1) circle [radius=3pt];
等于\fill (0.5cm, 0.5cm) circle (3pt);
不在任何网格点上。