我正在尝试在节点内部绘制并将线连接到其锚点。对于矩形形状,它工作得很好,但是当我尝试将两条线面对面连接时,如下例所示,仍然存在间隙。有人能帮我告诉我如何消除间隙吗?
节点周围的 [绘制] 只是为了定位,我想让边界保持不可见。
提前感谢您的帮助!
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
% define macro for drawing inside node
\newcommand{\myMacro}[1]{
\tikz[]{
\draw[thick] ([xshift=0.2mm]2*#1,0)
-- (2*#1,0)
arc (0:180:2*#1)
-- ([xshift=-0.2mm]-2*#1,0);
\draw[thick] (0,0) circle (#1);
\draw[thick] (0,-#1) -- (0,-2*#1);
}
}
% node with drawing inside
\node[inner sep=0, minimum size=0, outer sep=0, draw=black!20, very thin](n1) at (0,0) {\myMacro{0.15}};
% connect lines to node.
% blue circle: connection like it's supposed to be
% red circle: connection with gap! :-(
\draw[thick] (n1.west) node[draw=red, circle, inner sep=0.05cm, thin]{} -- ++(-0.5,0);
\draw[thick] (n1.east) -- ++(0.5,0);
\draw[thick] (n1.south) -- ++(0,-0.5);
\draw[thick] (n1.north) node[draw=blue, circle, inner sep=0.05cm, thin]{} -- ++(0,0.5);
\end{tikzpicture}
\end{document}
答案1
使用\pic
:
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}[thick, line cap=rect,
mypic/.pic = {
\draw (0,0) circle[radius=#1];
\draw (2*#1,0) coordinate (-e)
arc (0:90:2*#1) coordinate (-n)
arc (90:180:2*#1) coordinate (-w);
\draw (0,-#1) -- ++ (0,-#1) coordinate (-s);
}
]
\pic (n1) at (0,0) {mypic=0.15};
\draw (n1-e) -- ++ ( 0.5,0);
\draw (n1-w) -- ++ (-0.5,0);
\draw (n1-s) -- ++ (0,-0.5);
\draw (n1-n) -- ++ (0, 0.5);
%
\draw[blue, thin] (n1-n) circle[radius=0.5mm];
\draw[red, thin] (n1-w) circle[radius=0.5mm];
%
\node[draw=gray, very thin, inner sep=0pt,
fit=(n1-e) (n1-n) (n1-w) (n1-s)] {};
\end{tikzpicture}
\end{document}
答案2
嵌套 tikz 图片可能会带来很糟糕的结果。我会尽可能避免这样做。
据我所知,您只能嵌套 tikzpictures 才能使节点的坐标可用于进一步绘制。因此,一个简单的解决方法是使用图像内部周围的局部边界框:
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
% define macro for drawing inside node
\newcommand{\myMacro}[1]{
\draw[thick] ([xshift=0.2mm]2*#1,0)
-- (2*#1,0)
arc (0:180:2*#1)
-- ([xshift=-0.2mm]-2*#1,0);
\draw[thick] (0,0) circle (#1);
\draw[thick] (0,-#1) -- (0,-2*#1);
}
% node with drawing inside
\begin{scope}[local bounding box=n1]
\myMacro{0.15};
\end{scope}
% connect lines to node.
% blue circle: connection like it's supposed to be
% red circle: connection with gap! :-(
\draw[thick] (n1.west) node[draw=red, circle, inner sep=0.05cm, thin]{} -- ++(-0.5,0);
\draw[thick] (n1.east) -- ++(0.5,0);
\draw[thick] (n1.south) -- ++(0,-0.5);
\draw[thick] (n1.north) node[draw=blue, circle, inner sep=0.05cm, thin]{} -- ++(0,0.5);
\end{tikzpicture}
\end{document}