I've been searching around but I can't find any info for adding an image background for my code listing using the listings
package. Is there a way to do this?
-
1There is (always? ;-)) a way via TikZ...– Paul GaboritJul 17, 2012 at 7:01
-
Follow up Question: Background images for code listings in beamer.– Peter GrillJul 21, 2012 at 18:33
1 Answer
As PolGab says, there is always a tikz
way. Here is one that uses the infamous \tikzmark
to mark the begin and end of the listing, and then adds an image clipped to the size of the listing:
Note:
This does require two runs. First one to determine the locations, and the second to do the drawing.
The
\tikzmark
is from Adding a large brace next to a body of text.
Issues:
This however has some serious issues:
A blank line is required before the listing (surprising result otherwise).
Not sure why the fudge facts were required, but they end up aligning the frame to pretty close to where the
fram=tb
option would have drawn the horizontal lines.
Code:
\documentclass{article}
\usepackage{listings}
\usepackage{graphicx}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{decorations.pathreplacing}
\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}
\newcommand*{\AddBackgroundImage}[4][]{%
%\pgfmathsetmacrp{\height}{}%
\begin{tikzpicture}[overlay,remember picture]
\coordinate (VCenter) at ($(#2)!0.5!(#3)$);
\coordinate (Fudge) at (-\pgflinewidth,0);
\coordinate (VFudge) at (0,\baselineskip);
%\draw [red, thick,fill=yellow, fill opacity=0.2]% for debugging
\clip
($(#2)+ (Fudge) - 0.50*(VFudge)$) --
($(#2) + (\linewidth,0) - 0.50*(VFudge)$) --
($(#3) + (\linewidth,0) + 1.25*(VFudge)$) --
($(#3)+ (Fudge) + 1.25*(VFudge)$) -- cycle;
\path (VCenter) -- ++($(0.5*\linewidth,0)$)
node [opacity=0.3, #1] {\includegraphics[width=\linewidth]{#4}};
\end{tikzpicture}%
}%
\lstset{
language=C,
basicstyle=\small\sffamily,
%frame=tb,
numbers=left,
xleftmargin=5.0ex,
numberstyle=\tiny,
numbersep=4pt,
stepnumber=2,
keywordstyle=\color{blue}\bfseries
}
\lstset{emph={% Adjust any special keywords
printf%
},emphstyle={\color{red}\bfseries}%
}%
\begin{document}
\noindent
Here is an example of listings with a background image:
\noindent% Line above MUST be blank
\tikzmark{Start}%
\begin{lstlisting}
/* Hello World program */
#include<stdio.h>
struct cpu_info {
long unsigned utime, ntime, stime, itime;
long unsigned iowtime, irqtime, sirqtime;
};
main()
{
printf("Hello World");
}\end{lstlisting}
\tikzmark{End}
\AddBackgroundImage{Start}{End}{images/EiffelWide}%
%
\noindent
Some text afterwards.
\end{document}
-
2Very beautiful background... But the original question is "It there a way to do this" and not "How to do this". ;-) Jul 17, 2012 at 11:49
-
3
-
Tried using this technique with the beamer package. Did not work. I just get a grey box around the listing.– EricJul 21, 2012 at 16:49
-
If the codes are long enough to span multiple pages, then what happen? :-) Jul 21, 2012 at 17:02
-