我正在尝试在我的文档中包含一个图像:
\documentclass[a4paper,10pt,twoside]{book}
\usepackage{graphicx}
\begin{document}
\def\foo{scale=0.1}
\includegraphics[\foo]{fig1.eps}
\end{document}
给了我错误
ERROR: Package xkeyval Error: `scale=0.1' undefined in families `Gin'.
这与宏扩展有关,但我无法解决。然后我看到了这有以下答案的问题
定义私有
\includegraphics
允许您将宏作为可选参数调用:\protected\def\newincludegraphics{\@testopt\new@includegraphics{}} \def\new@includegraphics[#1]{% \begingroup \@protected@edef\x{\endgroup \noexpand\includegraphics \if\relax\detokenize{#1}\relax\else[#1]\fi }\x } \newincludegraphics[\scalefactor]{image}
新的宏\newincludegraphics
被定义的地方。
平均能量损失
\documentclass[a4paper,10pt,twoside]{book}
\usepackage{graphicx}
\begin{document}
\protected\def\newincludegraphics{\@testopt\new@includegraphics{}}
\def\new@includegraphics[#1]{%
\begingroup
\@protected@edef\x{\endgroup
\noexpand\includegraphics
\if\relax\detokenize{#1}\relax\else[#1]\fi
}\x
}
\def\foo{scale=0.1}
\newincludegraphics[\foo]{fig1.eps}
\end{document}
尽管如此我仍然收到此错误:
ERROR: You can't use `\spacefactor' in vertical mode.
--- TeX said ---
\@->\spacefactor
\@m
l.62 \newincludegraphics
[scale=0.1]{fig1.eps}
这个错误可能是什么原因造成的?有没有无需定义另一个宏来包含图形的解决方法?
答案1
keyval 解析器不会扩展宏,但你可以这样做
\expandafter\includegraphics\expandafter[\foo]{fig1.eps}
\foo
如果需要的话,先进行扩展。
答案2
您可以定义一个新键:
\documentclass[a4paper,10pt,twoside]{book}
\usepackage{graphicx}
\makeatletter
\define@key{Gin}{foo}[]{\setkeys{Gin}{scale=0.1}}
\makeatother
\begin{document}
\includegraphics[foo]{example-image.pdf}
\end{document}
的第二个参数\setkeys
不展开,而可选参数\includegraphics
类似于
\includegraphics[<whatever>]{file}
基本上是作为来管理的\setkey{Gin}{<whatever>}
。