![在 TikZ 节点标签内使用多种样式](https://linux22.com/image/338656/%E5%9C%A8%20TikZ%20%E8%8A%82%E7%82%B9%E6%A0%87%E7%AD%BE%E5%86%85%E4%BD%BF%E7%94%A8%E5%A4%9A%E7%A7%8D%E6%A0%B7%E5%BC%8F.png)
我想做这样的事:
在 TikZ 中使用 PGF 样式
以下是代码:
\documentclass[tikz,convert={outfile=mwe.png}]{standalone}
\begin{document}
\pgfkeys{%
/tikz/style A/.style = {text=blue},
/tikz/style B/.style = {text=red},
}
\begin{tikzpicture}
\node [thin, draw, style A] at (1,3) {Style A};
\node [thin, draw, style B] at (1,2) {Style B};
\node [thin, draw] at (1,1) {Style A + Style B};
\end{tikzpicture}
\end{document}
但是“样式 A + 样式 B”的颜色始终相同。我该如何将“样式 A”style A
和“样式 B”style b
以及“+”添加到节点样式中?
当然我可以使用类似的东西{\color{blue}Style A} + {\color{red}Style B}
,但它不太灵活。我更喜欢使用样式。
提前致谢。
答案1
如果你想让它适用于任何文本然后我可以看到两个选项,它们允许您保持灵活性,因为您只需要更改颜色一次。
第一种方法是\colorlet
定义要使用的颜色,然后通过应用您提出的解决方案\textcolor
。
\colorlet{StyleAColor}{blue}
\colorlet{StyleBColor}{red}
\tikzset{
style A/.style={text=StyleAColor},
style B/.style={text=StyleBColor},
}
\node [thin, draw] at (1,1) {\textcolor{StyleAColor}{Style A} + \textcolor{StyleBColor}{Style B}};
第二种选择是嵌套tikzpictures
,这是不是受到推崇的:
\node [thin, draw] at (1,0) {
{\tikz[baseline=0pt] \node[style A, Inner Style] {Style A};}
{\tikz[baseline=0pt] \node[Inner Style] {+};}
{\tikz[baseline=0pt] \node[style B, Inner Style] {Style B};}
代码:
\documentclass[border=2pt]{standalone}
\usepackage{tikz}
\usepackage{xcolor}
\colorlet{StyleAColor}{blue}
\colorlet{StyleBColor}{red}
\tikzset{
Inner Style/.style={inner sep=0pt, outer sep=0pt},
style A/.style={text=StyleAColor},
style B/.style={text=StyleBColor},
}
\begin{document}
\begin{tikzpicture}
\node [thin, draw, style A] at (1,3) {Style A};
\node [thin, draw, style B] at (1,2) {Style B};
\node [thin, draw] at (1,1) {\textcolor{StyleAColor}{Style A} + \textcolor{StyleBColor}{Style B}};
\node [thin, draw] at (1,0) {
{\tikz[baseline=0pt] \node[style A, Inner Style] {Style A};}
{\tikz[baseline=0pt] \node[Inner Style] {+};}
{\tikz[baseline=0pt] \node[style B, Inner Style] {Style B};}
};
\end{tikzpicture}
\end{document}
答案2
根据@peter-grill的回答(感谢他),我想出了满足我需求的解决方案:
\documentclass[tikz,convert={outfile=mwe.png}]{standalone}
\begin{document}
\pgfkeys{%
/tikz/Inner Style/.style={ultra thin, draw},
/tikz/style A/.style = {text=blue},
/tikz/style B/.style = {text=red},
/tikz/nested/.style = {%
baseline=(current bounding box.base),
every node/.append style={inner sep=0pt, outer sep=0pt, anchor=base, Inner Style},
},
}
\begin{tikzpicture}
\node [thin, draw, nested] at (1,-1) {%
{\tikz \node[style A]{e};}%
{\tikz \node[]{epe};}%
{\tikz \node[style B]{e};}
};
\node [thin, draw, nested] at (1,0) {%
{\tikz \node[style A]{Style a};}%
{\tikz \node[]{+};}%
{\tikz \node[style B]{Style b};}
};
\end{tikzpicture}
\end{document}
注意:诀窍在于使用baseline
和anchor
选项。