如何在 TikZ 中使用 documentclass=standalone 绘制线条时去除空白?

如何在 TikZ 中使用 documentclass=standalone 绘制线条时去除空白?

我渲染的图形中出现了令人讨厌的空白,其中的线条以页面边框为起点或终点。我使用的是“独立”文档类,因为实际上没有这些边距。

让我们假设我的 TikZ 图形的代码如下。

\documentclass[tikz]{standalone}

\usepackage{tikz}
\usepackage{color}

\begin{document}

    \begin{tikzpicture}
        %   simple gray box
        \fill[darkgray] (0, 0) rectangle (2, 2);
        %   green line beginning from the left
        \draw[green, line width=0.5cm] (0, 1) -- (1, 1);
    \end{tikzpicture}

\end{document}

使用上面的 TeX 代码我得到了这幅图像(放大以便更好地看清我的意思):

左侧不需要的空白

通过使用鼠标拖动该图像,您肯定会注意到图像的左边框和灰色框(图像实际开始的位置)之间存在一些空白。

是的,我知道如果我像这样画线的话,这个空白就完全有意义了:

\draw[green, line width=0.5cm] (0, 1.5) -- (0, 1) -- (1, 1);

…但我没有。

在我的例子中,我只需要从左到右绘制水平线,而不需要沿着边框绘制。我还在背景中使用了深色框,就像上例中的灰色框一样。所以,那个空白真的让我很烦恼。

我怎样才能摆脱它?

答案1

一个(可能不太好的)解决方案是沿着您希望图片适合的边框剪切图片,在本例中是黑色矩形的边框。

\documentclass[tikz]{standalone}

\usepackage{tikz}
\usepackage{color}

\begin{document}

    \begin{tikzpicture}
        \clip (0, 0) rectangle (2, 2);
        \fill[darkgray] (0, 0) rectangle (2, 2); 
        \draw[green, line width=0.5cm] (0, 1) -- (1, 1);
    \end{tikzpicture}

\end{document}

在此处输入图片描述

相关内容