在以下示例中,标签位于线的中间。但充当标记的箭头并不在中间。只有箭头的头部在中间,而箭头的中心不在中间。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows,decorations.markings}
\begin{document}
\begin{tikzpicture}[
middlearrow/.style 2 args={
decoration={
markings,
mark=at position 0.5 with {\arrow{triangle 45}, \node[#1] {#2};}
},
postaction={decorate}
}
]
\draw[middlearrow={below}{+}] (0,0) -- (1,0);
\end{tikzpicture}
\end{document}
答案1
值得注意的是,该markings
机制将箭头置于选定的position
位置,并以箭头的箭头为参考。以下示例清楚地说明了这一点:
\documentclass[tikz,border=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows,decorations.markings,plotmarks}
\begin{document}
\begin{tikzpicture}[
middlearrow/.style 2 args={
decoration={
markings,
mark=at position 0.5 with {\arrow{triangle 45}, \node[#1] {#2};}
},
postaction={decorate}
},
my mark/.style={
decoration={
markings,
mark=at position 0.5 with{\color{red}\pgfuseplotmark{x}},
},
postaction=decorate,
}
]
\draw[middlearrow={below}{+},my mark] (0,0) -- (1,0);
\draw[middlearrow={below}{+},my mark] (0,-1) -- (2,-1);
\draw[middlearrow={below}{+},my mark] (0,-2) -- (4,-2);
\end{tikzpicture}
\end{document}
那该怎么办?史蒂文展示了一种可能性。只需使用 TikZ 选项,即可轻松采用相同的方法,具体如下xshift
:
\documentclass[tikz,border=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows,decorations.markings,plotmarks}
\begin{document}
\begin{tikzpicture}[
middlearrow/.style 2 args={
decoration={
markings,
mark=at position 0.5 with {\arrow[xshift=3.333pt]{triangle 45}, \node[#1] {#2};}
},
postaction={decorate}
},
]
\draw[middlearrow={below}{+}] (0,0) -- (1,0);
\draw[middlearrow={below}{+}] (0,-1) -- (2,-1);
\draw[middlearrow={below}{+}] (0,-2) -- (4,-2);
\end{tikzpicture}
\end{document}
“魔法数字”似乎是正确的。为了真正精确,应该进入pgflibraryarrows.code.tex
文件并计算箭头的准确宽度triangle 45
。
此解决方案不能防止改变线宽时出现错误。
答案2
箭头和加号都向右移动了\makebox
,似乎可以在各种长度范围内工作。不过,我猜想,标记框的实际大小将取决于箭头的大小。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows,decorations.markings}
\begin{document}
\begin{tikzpicture}[
middlearrow/.style 2 args={
decoration={
markings,
mark=at position 0.5 with {%
\makebox[4pt][r]{\arrow{triangle 45}}, \node[#1] {#2};}
},
postaction={decorate}
}
]
\draw[middlearrow={below}{\makebox[1pt][r]{+}}] (0,0) -- (1,0);
\draw[middlearrow={below}{\makebox[1pt][r]{+}}] (0,-.5) -- (2,-.5);
\draw[middlearrow={below}{\makebox[1pt][r]{+}}] (0,-1) -- (3,-1);
\end{tikzpicture}
\end{document}