【LaTeX应用】在有程序代码的图片中添加注释内容

在计算机专业书籍或者文章中,经常会用到代码,比如C语言代码,如何在代码中添加注释,用图片的形式展示,这种排版很常见,但是用latex怎么实现?

如图所示的效果,在latex排版中如何实现?完整代码如下

\documentclass[svgnames]{book}

\usepackage{ctex}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usepackage{listings}
\lstset{%
	frame            = tb,    % draw frame at top and bottom of code block
	tabsize          = 1,     % tab space width
	numbers          = left,  % display line numbers on the left
	framesep         = 3pt,   % expand outward
	framerule        = 0.4pt, % expand outward 
	commentstyle     = \color{Green},      % comment color
	keywordstyle     = \color{blue},       % keyword color
	stringstyle      = \color{DarkRed},    % string color
	backgroundcolor  = \color{WhiteSmoke}, % backgroundcolor color
	showstringspaces = false,              % do not mark spaces in strings
}

\begin{document}
	
	\begin{lstlisting}[language = C++, numbers = none, escapechar = !,
	basicstyle = \ttfamily\bfseries, linewidth = .6\linewidth] 
	int!
	\tikz[remember picture] \node [] (a) {};
	!puissance!
	\tikz[remember picture] \node [] (b) {};
	!(int x,!
	\tikz[remember picture] \node [] (c){};
	!int n) { 
	
		int i, p = 1; !\tikz[remember picture] \node [] (d){};!           
		
		for (i = 1; i <= n; i++) 
			p = p * x; !\tikz[remember picture] \node [inner xsep = 40pt] (e){};! 
		
		return p; !
		\tikz[remember picture] \node [] (f){};!  
	}
	\end{lstlisting}
	\begin{tikzpicture}[remember picture, overlay,
	every edge/.append style = { ->, thick, >=stealth,DimGray, dashed, line width = 1pt },
	every node/.append style = { align = center, minimum height = 10pt,	font = \bfseries, fill= green!20},
	text width = 2.5cm ]
	
	\node [above left = .75cm and -.75 cm of a,text width = 2.2cm]	(A) {函数返回值类型};
	\node [right = 0.25cm of A, text width = 1.9cm]	(B) {函数名称};
	\node [right = 0.5cm of B] (C) {函数的参数列表};
	\node [right = 4.cm of d]  (D) {变量声明};
	\node [right = 2.cm of e]  (E) {乘法运算};
	\node [right = 5.cm of f]  (F) {函数返回值};  
	
	\draw (A.south) + (0, 0) coordinate(x1) edge (x1|-a.north);
	\draw (B.south) + (0, 0) coordinate(x2) edge (x2|-b.north);
	\draw (C.south) + (0, 0) coordinate(x3) edge (x3|-c.north);
	\draw (D.west) edge (d.east) ;
	\draw (E.west) edge (e.east) ;  
	\draw (F.west) edge (f.east) ;
	\end{tikzpicture} 
	
\end{document}

本案例中只是以一个简单的例子做演示,基本逻辑结构不会改变,在具体的实际应用中可以对样式进行调整,如果对画图还不是很了解的话,可以看看小编其他绘图相关的教程

猜你喜欢

转载自blog.csdn.net/m0_50984266/article/details/111416945