![算法片段的框架](https://linux22.com/image/257236/%E7%AE%97%E6%B3%95%E7%89%87%E6%AE%B5%E7%9A%84%E6%A1%86%E6%9E%B6.png)
我想在算法的片段周围添加框架,如下图所示。如果矩形的背景可以更改,那就太好了。
这是该算法使用的 LaTeX 代码。
\documentclass[10pt,a4paper]{article}
\usepackage[ruled]{algorithm2e}
\begin{document}
\begin{algorithm}[H]
\caption{Le crible d'Eratosthène}
\KwData{la liste $L$ des naturels compris de $2$ à $N$.}
\KwResult{la liste $P$ des nombres premiers compris entre $2$ et $N$.}
\BlankLine
\For{$i = 2$ \KwTo $N$}{
\If{$i$ n'est pas barré dans la liste $L$}{
Barrer dans la liste $L$ les mutltiples $ki$ où $k \geq 2$.
}
}
\Return{la liste $P$ des nombres non barrés.}
\end{algorithm}
\end{document}
答案1
\tikzmark
该\MyBox
命令允许绘制彩色框架;语法是
\MyBox[<vertical offset>]{<mark>}{<mark>}{<color>}
一个例子:
\documentclass[10pt,a4paper]{article}
\usepackage[ruled]{algorithm2e}
\usepackage{tikz}
\usetikzlibrary{calc,fit}
% code by Andrew Stacey
% http://tex.stackexchange.com/a/50054/3954
\makeatletter
\tikzset{%
remember picture with id/.style={%
remember picture,
overlay,
save picture id=#1,
},
save picture id/.code={%
\edef\pgf@temp{#1}%
\immediate\write\pgfutil@auxout{%
\noexpand\savepointas{\pgf@temp}{\pgfpictureid}}%
},
if picture id/.code args={#1#2#3}{%
\@ifundefined{save@pt@#1}{%
\pgfkeysalso{#3}%
}{
\pgfkeysalso{#2}%
}
}
}
\def\savepointas#1#2{%
\expandafter\gdef\csname save@pt@#1\endcsname{#2}%
}
\def\tmk@labeldef#1,#2\@nil{%
\def\tmk@label{#1}%
\def\tmk@def{#2}%
}
\tikzdeclarecoordinatesystem{pic}{%
\pgfutil@in@,{#1}%
\ifpgfutil@in@%
\tmk@labeldef#1\@nil
\else
\tmk@labeldef#1,(0pt,0pt)\@nil
\fi
\@ifundefined{save@pt@\tmk@label}{%
\tikz@scan@one@point\pgfutil@firstofone\tmk@def
}{%
\pgfsys@getposition{\csname save@pt@\tmk@label\endcsname}\save@orig@pic%
\pgfsys@getposition{\pgfpictureid}\save@this@pic%
\pgf@process{\pgfpointorigin\save@this@pic}%
\pgf@xa=\pgf@x
\pgf@ya=\pgf@y
\pgf@process{\pgfpointorigin\save@orig@pic}%
\advance\pgf@x by -\pgf@xa
\advance\pgf@y by -\pgf@ya
}%
}
\newcommand\tikzmark[2][]{%
\tikz[remember picture with id=#2] #1;}
\makeatother
% end of code by Andrew Stacey
\newcommand\MyBox[4][-1ex]{%
\tikz[remember picture,overlay,pin distance=0cm]
{\draw[draw=#4,line width=1pt,fill=#4!20,rectangle,rounded corners]
( $ (pic cs:#2) + (-1ex,2ex) $ ) rectangle ( $ (pic cs:#3) + (1ex,#1) $ );
}
}
\begin{document}
\MyBox{starta}{enda}{blue}
\MyBox[-3ex]{startb}{endb}{red}
\begin{algorithm}[H]
\caption{Le crible d'Eratosthène}
\tikzmark{starta}\KwData{la liste $L$ des naturels compris de $2$ à $N$.}
\KwResult{la liste $P$ des nombres premiers compris entre $2$ et $N$.\tikzmark{enda}}
\BlankLine
\For{$i = 2$ \KwTo $N$}{
\tikzmark{startb}\If{$i$ n'est pas barré dans la liste $L$}{
Barrer dans la liste $L$ les mutltiples $ki$ où $k \geq 2$.\tikzmark{endb}
}
}
\Return{la liste $P$ des nombres non barrés.}
\end{algorithm}
\end{document}