\includegraphics 在圖形環境內部和外部工作方式不同

\includegraphics 在圖形環境內部和外部工作方式不同

我想重新定義\includegraphics,以便當它在環境中照常工作時figure,它會在環境之外自動居中figure

這是我的嘗試:

\documentclass{article}
\usepackage{graphicx}
\makeatletter
\let\old@includegraphics\includegraphics
\renewcommand\includegraphics[2][]{
    \ifx\@currenvir\@figureenvname
        \old@includegraphics[#1]{#2}
    \else
        \begin{center}\old@includegraphics[#1]{#2}\end{center}
    \fi}
\newcommand*\@figureenvname{figure}
\makeatother
\begin{document}
\includegraphics[width=0.4\textwidth]{example-image-a}
\begin{figure}[ht]
    \includegraphics[width=0.4\textwidth]{example-image-a}
\end{figure}
\end{document}

這按預期工作(第一個數字居中,第二個數字左對齊)。

但是一旦我在 中使用此命令beamer,它就不再起作用:

\documentclass{beamer}
\usepackage{graphicx}
\makeatletter
\let\old@includegraphics\includegraphics
\renewcommand\includegraphics[2][]{
    \ifx\@currenvir\@figureenvname
        \old@includegraphics[#1]{#2}
    \else
        \begin{center}\old@includegraphics[#1]{#2}\end{center}
    \fi}
\newcommand*\@figureenvname{figure}
\makeatother
\begin{document}
\begin{frame}
\includegraphics[width=0.4\textwidth]{example-image-a}
\begin{figure}[ht]
    \includegraphics[width=0.4\textwidth]{example-image-a}
\end{figure}
\end{frame}
\end{document}

兩個數字均居中。問題是什麼?我該如何修復它?

相關內容