问题描述
我为数学笔记创建了一个示例环境。它以示例的标题为输入,并用tikz绘制了一些线。但是,这样做需要标题的长度。
当仅通过使用\newlength{\lengthname}
后跟\settowidth{\lengthname}{[length]}
调用一次环境时,这相对容易实现。但是,一旦多次调用它,就必须定义一个不同的长度。我的(很糟糕)的解决方法是,每次使用示例环境时,都要传递不同长度的名称#2
。
每次使用环境时如何创建唯一的\newlength{\unique}
,还是有更好的方法实现目标?
\newenvironment{example}[2] % Example Environment
{\refstepcounter{example}
\newlength{#2}
\settowidth{#2}{\small \textbf{Example \thesection.\theexample} --- #1}
\bigskip\begin{tikzpicture}
\draw (-0.5\columnwidth,-0.2)--(-0.5\columnwidth,0)--(0.5\columnwidth,-0.2);
\fill[white] (-0.5#2-5pt,-1pt) rectangle (0.5#2+5pt,1pt);
\tikzlabel{0}{-0.4}{\text{\small \textbf{Example \thesection.\theexample} --- #1}}
\end{tikzpicture}}
%
{\begin{tikzpicture}
\draw (-0.5\columnwidth,0.2) -- (-0.5\columnwidth,0) -- (0.5\columnwidth,0.2);
\end{tikzpicture}}
非常感谢。
解决方法
我的建议是使用tcolorbox而不是自己绘制框架,但是如果必须使用tikz,只需将白色背景用作标题即可。
请注意,您的代码将产生很多框溢出警告。您必须考虑缩进,并绘制一个不适合列的框架,因为您需要额外增加两倍的tikz线宽度的一半。我只是将宽度减小为.49\columnwidth
,但是您也可以在计算中考虑线的宽度。
还要注意---
周围的间距。如果您不阻止宏占用空间,那么它将不会居中。
\documentclass{article}
\usepackage{tikz}
\newcounter{example}
\newenvironment{example}[1]{%
\refstepcounter{example}%
\bigskip
\noindent%
\begin{tikzpicture}
\draw (-0.49\columnwidth,-0.2)--(-0.49\columnwidth,0)--(0.49\columnwidth,-0.2);
\node[fill=white,font=\small\bfseries] at (0,-1pt) {Example \thesection.\theexample{} --- #1};
\end{tikzpicture}%
\par%
}{%
\par%
\noindent%
\begin{tikzpicture}
\draw (-0.49\columnwidth,0.2) -- (-0.49\columnwidth,0) -- (0.49\columnwidth,0.2);
\end{tikzpicture}%
\par%
}
\begin{document}
\begin{example}{test}
content...
\end{example}
\end{document}