我将 TikZ 图形保存在包含所有必要定义的单独文件中,以便于重复使用它们。
在某些情况下,我定义了一种新的模式,例如
\pgfdeclarepatternformonly{wide lines}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{12pt}{12pt}}{\pgfqpoint{9pt}{9pt}}%
{
\pgfsetlinewidth{0.4pt}
\pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
\pgfpathlineto{\pgfqpoint{9pt}{9pt}}
\pgfusepath{stroke}
}
但是,如果我在同一个文档中使用两个这样的图形,pdflatex 会抱怨已经定义了模式。有什么方法可以检查具有该名称的模式是否已经定义,如果是,则跳过我的定义?
我查看了一下 pgf 源代码,但并没有真正理解它。
答案1
正如评论中提到的,我会将模式定义放在单独的文件中,然后导入定义文件。这样,定义就保持一致。
但是,如果您不想这样做,您可以使用\providepgfdeclarepatternformonly
这个\pgfdeclarepatternformonly
定义:
\makeatletter
\newcommand{\providepgfdeclarepatternformonly}[4][]{%
\pgfutil@ifundefined{pgf@pattern@name@#1}{
\pgfdeclarepatternformonly{#1}{#2}{#3}{#4}
}{%
%Pattern already defined, so don't redefine it
}%
}
\makeatother
类似于providecommand
,如果模式已经定义,则重新定义它的尝试将被忽略。以下是使用编译的测试用例providepgfdeclarepatternformonly
,但pgfdeclarepatternformonly
给出了有关模式已定义的错误。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{patterns}
\makeatletter
\newcommand{\providepgfdeclarepatternformonly}[5]{%
\pgfutil@ifundefined{pgf@pattern@name@#1}{%
\pgfdeclarepatternformonly{#1}{#2}{#3}{#4}{#5}%
}{%
%Pattern already defined, so don't redefine it
}%
}
\makeatother
\begin{document}
\providepgfdeclarepatternformonly{wide lines}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{12pt}{12pt}}{\pgfqpoint{9pt}{9pt}}%
{
\pgfsetlinewidth{0.4pt}
\pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
\pgfpathlineto{\pgfqpoint{9pt}{9pt}}
\pgfusepath{stroke}
}
\begin{tikzpicture}
\providepgfdeclarepatternformonly{wide lines}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{12pt}{12pt}}{\pgfqpoint{9pt}{9pt}}%
{
\pgfsetlinewidth{0.4pt}
\pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
\pgfpathlineto{\pgfqpoint{9pt}{9pt}}
\pgfusepath{stroke}
}
\filldraw[pattern=wide lines] (0,0) rectangle (2,2);
\end{tikzpicture}
\end{document}