我想知道是否有任何方法\pgfkeys
可以tikz
定义可选参数,如下面的代码所示:
代码:
\documentclass[a4paper]{article}
\usepackage{pgf,graphicx}
\usepackage{geometry}
\geometry{showframe}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\parindent0pt
\begin{document}
% #1 for optional args in the macro \includegraphics, "width=\linewidth", for example
% #2 is the name of an picture file
\pgfkeys{
c/.code args={[#1]{#2}}{\includegraphics[#1]{#2}}
}
\pgfkeys{c={logob}}%Same as \includegraphics{logob}
% The above code does not work because #1 is not given. How to make it work when optional args are not given?
\end{document}
答案1
类似下面的方法可以工作。key/c
接受单个参数,然后\includegraphics
根据 key 的值是否以 开头,调用不同形式的[
。
\documentclass{article}
\usepackage{graphicx}
\usepackage{pgfkeys}
\begin{document}
\makeatletter
\pgfkeys{
c/.code={%
\@ifnextchar[%]
{\includegraphics#1\mykeys@gobble@til@nil}
{\includegraphics{#1}\mykeys@gobble@til@nil}%
#1\@nil
}
}
\long\def\mykeys@gobble@til@nil#1\@nil{}
\makeatother
\pgfkeys{c={example-image}}
% Same as \includegraphics{...}
\pgfkeys{c={[width=3cm]{example-image}}}
% Same as \includegraphics[width=3cm]{...}
\end{document}