我想在 tikz 节点内渲染几行代码:
\usemodule[tikz]
\definetyping[code][bodyfont=small,escape={`,`}]
\starttext
\tikzset{
code/.style={rectangle, rounded corners, draw=black}
}
\starttikzpicture[node distance=.7cm]
\node[code] (g1) {
\startcode
i = 1
t1 = 20
iloop: if i > t1 goto iexit
\stopcode
};
\stoptikzpicture
\stoptext
其渲染效果为:
如您所见,所有换行符都消失了。我设法通过使用段落来增强这一点:
\usemodule[tikz]
\definetyping[code][bodyfont=small,escape={`,`}]
\defineparagraphs[CodeNode][n=1]
\setupparagraphs[CodeNode][1][width=.5\textwidth]
\starttext
\tikzset{
code/.style={rectangle, rounded corners, draw=black}
}
\starttikzpicture[node distance=.7cm]
\node[code] (g1) {
\startCodeNode
\startcode
i = 1
t1 = 20
iloop: if i > t1 goto iexit
\stopcode
\stopCodeNode
};
\stoptikzpicture
\stoptext
渲染结果为:
这更接近我想要的,但我现在需要给出一个特定的宽度。如何创建一个自动包含给定代码的节点而不给出宽度?
答案1
将代码封装在framed
环境中。(使用从花园开始“打造紧密垂直贴合”)
\usemodule[tikz]
\defineframed
[codeframed]
[frame=no,
width=fit,
align=right,
strut=no,
offset=0pt]
\definetyping
[code]
[bodyfont=small,
escape={`,`},
before={\startframed[codeframed]},
after={\stopframed}]
\starttext
\tikzset{
code/.style={rectangle, rounded corners, draw=black}
}
\starttikzpicture[node distance=.7cm]
\node[code] (g1) {
\startcode
i = 1
t1 = 20
iloop: if i > t1 goto iexit
\stopcode
};
\stoptikzpicture
\stoptext
framedtext
在我看来,使用看起来比解决方案更简洁的方法来达到同样的效果framed
。(感谢Hans 指出 location=none
)
\usemodule[tikz]
\defineframedtext
[codeframed]
[frame=no,
width=fit,
location=none,
offset=0pt]
\definetyping
[code]
[bodyfont=small,
escape={`,`},
before={\startcodeframed},
after={\stopcodeframed}]
\starttext
\tikzset{
code/.style={rectangle, rounded corners, draw=black}
}
\starttikzpicture[node distance=.7cm]
\node[code] (g1) {
\startcode
i = 1
t1 = 20
iloop: if i > t1 goto iexit
\stopcode
};
\stoptikzpicture
\stoptext
如果 TikZ 的使用不是强制性的,您可能想要framedtext
单独使用。
\defineframedtext
[codeframed]
[autowidth=force,corner=round]
\definetyping
[code]
[bodyfont=small,
escape={`,`},
before={\startcodeframed},
after={\stopcodeframed}]
\starttext
\startcode
i = 1
t1 = 20
iloop: if i > t1 goto iexit
\stopcode
\stoptext