我使用以下代码来显示 tikzpicture 代码。
有没有一种简单的方法可以自动显示代码(位于图片中央)而无需修改它。
\documentclass{article}
\usepackage{verbatim}
\usepackage{tikz}
\begin{document}
\begin{tabular}{cc}
\begin{tikzpicture}
\draw[thick, blue] (1,0) -- (0,0) -- (0,1) -- cycle;
\end{tikzpicture}
&
\textbackslash begin\{tikzpicture\}\\
& \textbackslash draw[thick, blue] (1,0) -- (0,0) -- (0,1) -- cycle;\\
& \textbackslash end\{tikzpicture\}
\\
\end{tabular}
\end{document}
答案1
你可以使用 中的样式pgfmanual
。详情可参阅这里。请注意,您可能需要修改路径
\input{/usr/local/texlive/2019/texmf-dist/doc/generic/pgf/macros/pgfmanual-en-macros.tex}
在您的机器上。
\documentclass{ltxdoc} % the pgf manual styles are based on ltxdoc
\usepackage{tikz}
% necessary for the manual styles:
\usepackage{calc}
\input{/usr/local/texlive/2019/texmf-dist/doc/generic/pgf/macros/pgfmanual-en-macros.tex}
\RequirePackage{pgfmanual}
\begin{document}
\begin{codeexample}[]
\begin{tikzpicture}
\draw[thick, blue] (1,0) -- (0,0) -- (0,1) -- cycle;
\end{tikzpicture}
\end{codeexample}
\end{document}
或者,你可以像 CarLaTeX 一样使用tcolorbox
。该包的作者为我们提供了一个看起来像 pgfmanual 的样式。
\documentclass{article}
\usepackage[most]{tcolorbox}
\pgfdeclarelayer{background}
\pgfsetlayers{background,main}
\lstdefinestyle{example}{style=tcblatex,
classoffset=0,
texcsstyle=*\color{blue},%
deletetexcs={begin,end},
moretexcs={,%
pgfdeclarehorizontalshading,pgfuseshading,node,
useasboundingbox,draw}%
classoffset=1,
keywordstyle=\color{blue},%
morekeywords={tikzpicture,shade,fill,draw,path,node,child,line,width,rectangle},
classoffset=0}
\tcbset{%
fillbackground/.style={before lower pre={%
\tikzset{every picture/.style={execute at end picture={\begin{pgfonlayer}{background}
\fill[yellow!25!white]
([xshift=-1mm,yshift=-1mm]current bounding box.south west) rectangle
([xshift=1mm,yshift=1mm]current bounding box.north east);
\end{pgfonlayer}}}}}},
explicitpicture/.style={before lower=\begin{center},after lower=\end{center},fillbackground}}
\newtcblisting{sidebyside}[2][]{%
enhanced,frame hidden,
top=0pt,bottom=0pt,left=0pt,right=0pt,arc=0pt,boxrule=0pt,
colback=blue!25!white,
listing style=example,
sidebyside,text and listing,text outside listing,sidebyside gap=2mm,
lefthand width=#2,tikz lower,fillbackground,
#1}
\begin{document}
\begin{sidebyside}[explicitpicture]{4.2cm}
\begin{tikzpicture}
\draw[thick, blue] (1,0) -- (0,0) -- (0,1) -- cycle;
\end{tikzpicture}
\end{sidebyside}
\end{document}
答案2
和tcolorbox
。
您可以根据自己的喜好进行定制。
\documentclass{article}
\usepackage{verbatim}
\usepackage{tikz}
\usepackage{tcolorbox}
\tcbuselibrary{listings}
\newtcblisting{mybox}{%
text side listing,
lefthand width=1.5cm,
}
\begin{document}
\begin{mybox}
\begin{tikzpicture}
\draw[thick, blue] (1,0) -- (0,0) -- (0,1) -- cycle;
\end{tikzpicture}
\end{mybox}
\end{document}