绘制等于文本宽度的 TikZ 框

绘制等于文本宽度的 TikZ 框

抱歉,如果之前已经问过这个问题——我依稀记得看到过一些与此相关的东西,但现在再也找不到了。

所以我从这里取了一个 TeXample:带有文本和数学的方框。我稍微修改了一下,让它变短了。现在的问题是,虽然我指定了框的宽度等于\textwidth,但它似乎比从左到右边距的区域要大一点,而且它也向右移动了(从showframe包中可以清楚地看出)。这里有什么问题?

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{shapes,decorations}
\usepackage{amsmath,amssymb}
\usepackage{showframe}

\begin{document}

\tikzstyle{mybox} = [draw=red, fill=blue!20, very thick,
    rectangle, rounded corners, inner sep=10pt, inner ysep=20pt]
\tikzstyle{fancytitle} =[fill=red, text=white]

\begin{tikzpicture}
\node [mybox] (box){%
    \begin{minipage}{\textwidth}
        Some text and math blah blah blah
        \begin{align}
            \dot{n} &= u\cos\psi -v\sin\psi \\
            \dot{e} &= u\sin\psi + v\cos\psi
        \end{align}
    \end{minipage}
};
\node[fancytitle, right=10pt] at (box.north west) {A fancy title};
\node[fancytitle, rounded corners] at (box.east) {$\clubsuit$};
\end{tikzpicture}%

\end{document}

在此处输入图片描述

答案1

默认情况下, A 的tcolorbox宽度与 一样宽\textwidth,因此您不必担心它的大小和位置。

\documentclass{article}

\usepackage[most]{tcolorbox}
\usepackage{amsmath,amssymb}
\usepackage{showframe}

\newtcolorbox{mybox}[2][]{%
    enhanced,
    title = #2, 
    attach boxed title to top left={%
        xshift=5mm, 
        yshift=-\tcboxedtitleheight/2, 
        yshifttext=-1mm},
    boxed title style={colback=red, sharp corners},
    colframe = red,
    colback = blue!20,  
    overlay = {\node[text=white, fill=red] at (frame.east) 
        {$\clubsuit$};},
    #1}


\begin{document}

\begin{mybox}{A fancy title}%
        Some text and math blah blah blah
        \begin{align}
            \dot{n} &= u\cos\psi -v\sin\psi \\
            \dot{e} &= u\sin\psi + v\cos\psi
        \end{align}
\end{mybox}

\end{document}

在此处输入图片描述

答案2

您已设置了inner sep = 10pt,因此您应该从的宽度中减去该值的两倍minipage,此外\noindent也是必需的。

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes,decorations}
\usepackage{amsmath,amssymb}
\usepackage{showframe}

\begin{document}

\tikzstyle{mybox} = [draw=red, fill=blue!20, very thick,
    rectangle, rounded corners, inner sep=10pt, inner ysep=20pt]
\tikzstyle{fancytitle} =[fill=red, text=white]

\noindent\begin{tikzpicture}
\node [mybox] (box){%
    \begin{minipage}{\dimexpr\textwidth-20pt}
        Some text and math blah blah blah
        \begin{align}
            \dot{n} &= u\cos\psi -v\sin\psi \\
            \dot{e} &= u\sin\psi + v\cos\psi
        \end{align}
    \end{minipage}
};
\node[fancytitle, right=10pt] at (box.north west) {A fancy title};
\node[fancytitle, rounded corners] at (box.east) {$\clubsuit$};
\end{tikzpicture}%

\end{document}

在此处输入图片描述

相关内容