将 tikz 图形缩放到 \textwidth 的百分比

将 tikz 图形缩放到 \textwidth 的百分比

用户问了一个问题关于将数字缩放为的因子\textwidth并得到如下答案:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
  \includegraphics[width=0.5\textwidth]{file}
\end{document}

不过,我不确定如何将其应用到我的文档中:

\documentclass{article}
\usepackage{graphicx}
\usepackage{tikz}
\begin{document}
  \begin{figure}[!h]
    \centering
    \begin{tikzpicture}
      %
    \end{tikzpicture}
    \caption{This figure has a width which is a factor of \\textwidt}
  \end{figure}
\end{document}

我试过了

\begin{figure}[!h, width=\textwidth]

但那没有用。

答案1

你需要tikzscale包装。保存内容

\begin{tikzpicture}
  \draw (0,0) circle (2cm);
  \node at (0,0) {Me};
\end{tikzpicture}

比如说myfig.tikz,使用\includegraphics

代码:

\documentclass{article}
\usepackage{tikz}
\usepackage{tikzscale}
\usepackage{filecontents}    %% only for this demo
\begin{filecontents*}{myfig.tikz}
  \begin{tikzpicture}
      \draw (0,0) circle (2cm);
      \node at (0,0) {Me};
  \end{tikzpicture}
\end{filecontents*}
\begin{document}
  \begin{figure}[htb]
    \centering
    \includegraphics[width=0.5\textwidth]{myfig.tikz}
    \caption{This figure has a width which is a factor of text width}
  \end{figure}

  \begin{figure}[htb]
    \centering
    \includegraphics[width=0.2\textwidth]{myfig.tikz}
    \caption{This figure has a width which is a factor of text width}
  \end{figure}
\end{document}

在此处输入图片描述

与 不同\resizebox,字体不会不适当缩放。如果您也想缩放字体,请使用\begin{tikzpicture}[transform shape]而不是\begin{tikzpicture}

来自:\resizeboxgraphicx

\documentclass{article}
\usepackage{tikz}

\begin{document}
  \begin{figure}[htb]
    \centering
    \resizebox{0.5\textwidth}{!}{%
    \begin{tikzpicture}
      \draw (0,0) circle (2cm);
      \node at (0,0) {Me};
  \end{tikzpicture}
    }%
    \caption{This figure has a width which is a factor of text width}
  \end{figure}

  \begin{figure}[htb]
    \centering
    \resizebox{0.2\textwidth}{!}{%
    \begin{tikzpicture}
      \draw (0,0) circle (2cm);
      \node at (0,0) {Me};
  \end{tikzpicture}
    }%
    \caption{This figure has a width which is a factor of text width}
  \end{figure}
\end{document}

在此处输入图片描述

答案2

您可能还想考虑包裹adjustbox

\documentclass{article}
\usepackage{graphicx,adjustbox}
\usepackage{tikz}
\begin{document}
\begin{figure}[!h]
  \centering
  \begin{tikzpicture}
    \draw (0,0) rectangle (10,2);
  \end{tikzpicture}
  \caption{This figure uses no factor}
\end{figure}

\begin{figure}[!h]
  \centering
  \begin{adjustbox}{max width=0.5\textwidth}
  \begin{tikzpicture}
    \draw (0,0) rectangle (10,2);
  \end{tikzpicture}
\end{adjustbox}
\caption{This figure uses 0.5 factor}
\end{figure}

\begin{figure}[!h]
  \centering
  \begin{adjustbox}{max width=0.7\textwidth}
  \begin{tikzpicture}
    \draw (0,0) rectangle (10,2);
  \end{tikzpicture}
\end{adjustbox}
\caption{This figure uses factor 0.7}
\end{figure}

\end{document}    

在此处输入图片描述

相关内容