在算法环境中应用背景颜色

在算法环境中应用背景颜色

我还没有找到在算法环境中添加背景颜色的简单解决方案。你能帮我添加背景吗?

这是我目前拥有的代码:

\documentclass{article}
\usepackage{amsmath, amsfonts, amssymb, amsthm, bm}
\usepackage{commath}
\usepackage{xcolor}
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
\newcommand\mycommfont[1]{\footnotesize\ttfamily\textcolor{blue}{#1}}
\SetCommentSty{mycommfont}

\begin{document}
\SetAlgoLined
\SetNlSty{textbf}{}{:}
\begin{algorithm}[H]
\DontPrintSemicolon
This is line one\\
This is line two numbered\\
This should be numbered\\
This should also be numbered
\caption{Unnumbered lines}
\end{algorithm}

\end{document} 

答案1

这就是我如何使具有灰色背景的算法居中:

\begin{center}
\colorbox[gray]{0.95}{
\begin{minipage}{0.65\textwidth}
\SetAlgoLined
\SetNlSty{textbf}{}{:}
\begin{algorithm}[H]
\DontPrintSemicolon
This is line one\\
This is line two numbered\\
This should be numbered\\
This should also be numbered
\caption{Unnumbered lines}
\end{algorithm}
\end{minipage}}
\end{center}

答案2

这是我对@Joe 上述评论的回答的第二部分:(由于声誉点数较低,我无法在答案的第一部分发布超过 8 个链接。)

现在我们用下面的代码来说明获得的RGB颜色规范:{239,240,241}

\documentclass{article}
\usepackage[linesnumbered,lined,commentsnumbered]{algorithm2e}
\usepackage[usenames,dvipsnames,svgnames]{xcolor}

\begin{document}
\begin{center}
     \colorbox[RGB]{239,240,241}{
         \begin{minipage}{.9\linewidth}
              \begin{algorithm}[H]
                    \SetAlgoLined
                    \KwData{this text}
                    \KwResult{how to write algorithm with \LaTeX2e }
                    initialization\;
                    \While{not at end of this document}{
                         read current\;
                         \eIf{understand}{
                             go to next section\;
                             current section becomes this one\;
                         }{
                             go back to the beginning of current section\;
                         }
                     }
                     \caption{How to write algorithms}
               \end{algorithm}
          \end{minipage}}
\end{center}
\end{document}

并输出以下内容:

在此处输入图片描述

答案3

这是我对@Joe 上述评论的回答的第一部分:(因为我的声誉点数不够)

回答:你的问题其实与颜色模型有关。请查看颜色模型Wiki 中的子部分rgb。我使用带有颜色规范的模型对@pzorba75 的代码进行了稍微修改{0.74,0.83,1}

\documentclass{article}
\usepackage[linesnumbered,lined,commentsnumbered]{algorithm2e}
\usepackage[usenames,dvipsnames,svgnames]{xcolor}

\begin{document}
\begin{center}
   \colorbox[rgb]{0.74,0.83,1}{
        \begin{minipage}{0.65\textwidth}
            \SetAlgoLined
            \SetNlSty{textbf}{}{:}
            \begin{algorithm}[H]
            \DontPrintSemicolon
                  This is line one\\
                  This is line two numbered\\
                  This should be numbered\\
                  This should also be numbered
                  \caption{Unnumbered lines}
                  \end{algorithm}
      \end{minipage}}
\end{center}
\end{document}

输出如下所示:在此处输入图片描述

评论:

当然,您可以选择不同的颜色规格。以下是一些可供选择的列表,点击此链接

相关内容