如何在图片之间共享 TikZ 样式而不使其在全球范围内可用?

如何在图片之间共享 TikZ 样式而不使其在全球范围内可用?

环境tikzpicture允许在方括号中定义图片中可用的样式。我想在多张图片之间共享样式,以便在一个地方编辑它们。我知道这可以通过全局变量,但我想避免让所有图片都使用这些样式。有没有办法选择性地将样式仅包含到我想要使用它们的图片环境中?

答案1

您可以定义一个“安装”更多样式的样式。例如,在下面的 MWE 中,我定义了一个b全局可用的样式,该样式反过来安装/设置样式c以使其可用。同样,我定义了一个a全局可用的样式,但被覆盖b。最后,我定义了一个e仅调整样式的样式a,而没有完全重新定义它。

\documentclass{article}

\usepackage{tikz}

\tikzset{
    a/.style={ % 'a' is globally available 
        draw=green,
        line width=2pt,
        dashed,
    },
    b/.style={ % 'b' installs 'c' and overwrites 'a'
        c/.style={
            draw=red,
            fill=blue,
            text=white,
        },
        a/.style={
            draw=blue,
            line width=1pt,
        },
    },
    e/.style={ % The 'e' style will only change 'a' a bit, but will not overwrite
        a/.append style={
            fill=gray,
        }
    }
}

\begin{document}
    \begin{tikzpicture}
        \node[a] {Text}; % 'a' is globally available
    \end{tikzpicture}

    \begin{tikzpicture}[b]
        \node[a] {Text}; % Having called 'b', 'a' is redefined
        \node[c] at (1,0) {Text}; % And 'c' is available only in this picture
    \end{tikzpicture}

    \begin{tikzpicture}
        \node[a] {Text};
        %\node[c] at (2,0) {Text}; % This will not compile, 'c' is unknown here
        \begin{scope}[b]
            \node[a] at (1,0) {Text}; % In this scope, 'a' is redefined by 'b'
            \node[c] at (2,0) {Text}; % Again 'c' is available due to 'b'
        \end{scope}
    \end{tikzpicture}

    \begin{tikzpicture}[b,e]
        \node[a] {Text}; % Now 'a' is not completely redefined, but is changed due to 'e'
    \end{tikzpicture}
\end{document}

上述代码的结果是:

在此处输入图片描述

相关内容