tikzpicture 下的背景

tikzpicture 下的背景

有很多问题,background但我还没有找到我想要的答案

我想在 tikzpicture 的结果下使用一张图片(旧纸)。

其实我的代码是

% !TEX TS-program = lualatex-dev
\documentclass{standalone} 
\usepackage{tikz}
\usepackage{graphicx}
\newlength{\mywidth}
\newlength{\myheight}

\makeatletter
\newcommand{\pictsize}[2]{ % #1 = width, #2 = height
 \pgfextractx{\@tempdima}{\pgfpointdiff{\pgfpointanchor{current bounding box}{south west}}
 {\pgfpointanchor{current bounding box}{north east}}}
 \global#1=\@tempdima
 \pgfextracty{\@tempdima}{\pgfpointdiff{\pgfpointanchor{current bounding box}{south west}}
 {\pgfpointanchor{current bounding box}{north east}}}
 \global#2=\@tempdima
}
\makeatother
\pgfdeclarelayer{background layer}
\pgfsetlayers{background layer,main}
\tikzset{paper/.style={%
execute at end picture={%
\pictsize{\mywidth}{\myheight}%
\begin{pgfonlayer}{background layer} 
\node[inner sep=0pt] (p) at (current bounding box.center)
     {\includegraphics[width=\mywidth,height=\myheight]{paper.png}};
\end{pgfonlayer}%
}}}

\begin{document} 

\begin{tikzpicture}[paper]
\coordinate (A) at (0,0);
\coordinate (B) at (6,6);
\draw[line width=1cm] (A) -- (B);
\end{tikzpicture}
\end{document}

我的问题:是否可以避免\newlength{\mywidth} \newlength{\myheight}使用命令\pictsize?tikzpicture 和背景必须具有相同的尺寸。仅使用 TikZ !

在此处输入图片描述

答案1

您可以使用边界框剪辑图像,假设默认尺寸足够大。

\documentclass{standalone} 
\usepackage{tikz}
\usepackage{graphicx}

\pgfdeclarelayer{background layer}
\pgfsetlayers{background layer,main}
\tikzset{paper/.style={%
execute at end picture={%
\begin{pgfonlayer}{background layer} 
\clip (current bounding box.south west) rectangle (current bounding box.north east);
\node[inner sep=0pt] (p) at (current bounding box.center)
     {\includegraphics{example-image}};
\end{pgfonlayer}%
}}}

\begin{document} 

\begin{tikzpicture}[paper]
\coordinate (A) at (0,0);
\coordinate (B) at (6,6);
\draw[line width=1cm] (A) -- (B);
\end{tikzpicture}
\end{document}

答案2

是的,当然。 pgf 将尺寸存储在pgf@picmaxx\pgf@picminxpgf@picmaxy和中\pgf@picminy,因此您可以直接使用它们。

\documentclass{standalone} 
\usepackage{tikz}
\pgfdeclarelayer{background layer}
\pgfsetlayers{background layer,main}
\makeatletter
\tikzset{paper/.style={%
execute at end picture={%
\begin{pgfonlayer}{background layer} 
\pgfmathsetmacro{\mywidth}{\pgf@picmaxx-\pgf@picminx}%
\pgfmathsetmacro{\myheight}{\pgf@picmaxy-\pgf@picminy}%
\node[inner sep=0pt] (p) at (current bounding box.center)
     {\includegraphics[width=\mywidth pt,height=\myheight pt]{example-image-duck}};
\end{pgfonlayer}%
}}}
\makeatother

\begin{document} 
\begin{tikzpicture}[paper]
\coordinate (A) at (0,0);
\coordinate (B) at (6,6);
\draw[line width=1cm] (A) -- (B);
\end{tikzpicture}
\end{document}

在此处输入图片描述

顺便说一句,tikz自动加载graphicx,所以这真的是“唯一的tikz”。;-)

相关内容