在嵌套命令调用中将 pgfkey 重置为默认值

在嵌套命令调用中将 pgfkey 重置为默认值

我创建了一个新命令,其参数可以是对同一命令的新调用。然后我如何将嵌套调用中的 pgfkeys 的值重置为默认值,以便它们不具有在命令的第一次调用中设置的值?具体来说,叠加图像的宽度变为 2cm,而不是默认值 6cm,因为宽度在父命令调用中设置为 2cm。我知道我可以使用\pgfkeys{/icon/.cd,overlay,width,#1)重置\width,但随后它会变为空,而不是默认值。

\documentclass{article}
\usepackage{tikz}
\usepackage{etoolbox}
\usepackage{overpic}

\pgfkeys{
    /icon/.cd,
    width/.store in = \width,
    width/.default = ,
    overlay/.store in = \overlay,
    overlay/.default = ,
    width,overlay,
}

\newcommand\icondefaults[1]{%
    \pgfkeys{/icon/.cd,#1}%
    \pgfkeys{
        width/.default = \width,
    }%
}
\newcommand{\icon}[2][]{%
    {%
        \pgfkeys{/icon/.cd,overlay,#1}% "overlay" to prevent infinite loop of overlays
        \def\options{}%
        \ifdefvoid{\width}{}{\edef\options{width=\width,\options}}%
        \ifdefvoid{\overlay}{%
            \edef\graphic{\noexpand\includegraphics[\options]{#2}}%
        }{%
            \edef\temp{\noexpand\begin{overpic}[\options]{#2}}%
            \def\graphic{\temp\put(0,0){\overlay}\end{overpic}}%
        }%
        \graphic%
    }%
}%

\begin{document}

\icondefaults{width=6cm}
\icon{example-image} % Image gets default width 6cm
\icon[width=2cm,overlay={\icon{example-image-overlay}}]{example-image} % Image gets width 2cm, but the overlaid image also gets width 2cm
\icon{example-image} % Image gets default width 6cm

\end{document}

顺便说一句,抱歉%。我还不明白什么时候需要它们,现在还没有。

答案1

我找到了解决问题的方法。以下代码非常有效。希望它能对某人有所帮助 :)

\documentclass{article}
\usepackage{tikz}
\usepackage{etoolbox}
\usepackage{overpic}

\pgfkeys{
    /icon/.cd,
    width/.initial,
    overlay/.initial,
    overlay/.store in=\iconoverlay,
    set defaults/.unknown/.code={\pgfkeys{/icon/\pgfkeyscurrentname/.default=#1}}
}
\newcommand\icondefaults[1]{%
    \pgfkeys{/icon/set defaults/.cd, #1}%
}
\newcommand\ifkeyempty[3]{%
    \pgfkeysgetvalue{#1}{\keyvalue}%
    \ifempty{\keyvalue}{#2}{#3}%
}
\newcommand\ifempty[3]{%
    \def\novalue{\pgfkeysnovalue}%
    \def\empty{}%
    \ifboolexpr{test {\ifdefequal{#1}{\empty}} or test {\ifdefequal{#1}{\novalue}}}{#2}{#3}%
}
\newcommand{\icon}[2][]{%
    {%
        \pgfkeys{/icon/.cd,width,overlay,#1}% Reset to default values
        \def\options{}%
        \ifkeyempty{/icon/width}{}{\edef\options{width=\pgfkeysvalueof{/icon/width},\options}}%
        \ifempty{\iconoverlay}{%
            \edef\graphic{\noexpand\includegraphics[\options]{#2}}%
        }{%
            \edef\overlay{\noexpand\begin{overpic}[\options]{#2}}%
            \def\graphic{\overlay\put(0,0){\iconoverlay}\end{overpic}}%
        }%
        \graphic%
    }%
}%

\begin{document}

\icondefaults{width=6cm}
\icon{example-image} % Image gets default width 6cm
\icon[width=2cm,overlay={\icon{example-image-overlay}}]{example-image} % Image gets width 2cm, while the overlaid image gets default width 6cm
\icon{example-image} % Image gets default width 6cm

\end{document}

相关内容