我正在用 tikz 注释图片。
我努力了
\documentclass[tikz]{standalone}
\usetikzlibrary{shapes,arrows,positioning,decorations.pathreplacing}
\begin{document}
\tikzset{%
box/.style = {red, thick, rounded corners},
arrow/.style = {->, green, ultra thick},
}
\begin{tikzpicture}[node distance=0.1cm, auto]
% image
\node[anchor=south west,inner sep=0] (image) at (0,0) {%
\includegraphics[width=0.9\textwidth]{img/navbar.PNG}
};
% annotate
\begin{scope}[x={(image.south east)},y={(image.north west)}]
\draw[box] (0.02,0.15) rectangle (0.1,0.9);
\node at (-0.02,-1) {Home};
\draw[arrow] (0,-0.8) -- (0.02,0.15);
\end{scope}
\end{tikzpicture}
\end{document}
我的代码可以运行,但我手动放置了带有文本“Home”的节点。我必须绘制多个框,每个框中都有文本。我还想要一个从文本到文本所属框的箭头。
我可以使用一些定位魔法吗?我曾尝试命名绘制的矩形,\draw[box] (home) (0.02,0.15) rectangle (0.1,0.9);
但显然不允许像命名节点那样命名矩形。
答案1
您可以在矩形的一角添加coordinate
,使用语法绘制一条相对于此端点的线++(x,y)
,并Home
在线的末端添加节点。根据shorten <
您的喜好调整 的值。
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{shapes,arrows,positioning,decorations.pathreplacing}
\begin{document}
\tikzset{%
box/.style = {red, thick, rounded corners},
arrow/.style = {->, green, ultra thick},
}
\begin{tikzpicture}[node distance=0.1cm, auto]
% image
\node[anchor=south west,inner sep=0] (image) at (0,0) {%
\includegraphics[width=0.9\textwidth]{example-image}
};
% annotate
\begin{scope}[x={(image.south east)},y={(image.north west)}]
\draw[box] (0.02,0.15) coordinate(box1) rectangle (0.1,0.9);
\draw [arrow,shorten <=1pt] (box1) -- ++(-0.1,-0.7) node[below,black]{Home};
\end{scope}
\end{tikzpicture}
\end{document}
答案2
只是为了好玩,我创建了一个宏来根据节点的角生成一个节点。这实际上会给你一个带有锚点的框。
\documentclass[tikz]{standalone}
\usepackage{mwe}% for example=image
\usetikzlibrary{shapes,arrows,positioning,decorations.pathreplacing,calc}
\newlength{\boxnodewidth}
\newlength{\boxnodeheight}
\newcommand{\boxnode}[4][\empty]% #1=parms (aptional), #2 = name, #3=SE corner x,y, #4=NW corner x,y
{\coordinate (boxnodecornerse) at (#3);
\coordinate (boxnodecornernw) at (#4);
\pgfextractx{\boxnodewidth}{\pgfpointdiff{\pgfpointanchor{boxnodecornerse}{center}}%
{\pgfpointanchor{boxnodecornernw}{center}}}%
\pgfextracty{\boxnodeheight}{\pgfpointdiff{\pgfpointanchor{boxnodecornerse}{center}}%
{\pgfpointanchor{boxnodecornernw}{center}}}%
\node[minimum width=\boxnodewidth,minimum height=\boxnodeheight,inner sep=0pt,#1] (#2) at ($(boxnodecornerse)!.5!(boxnodecornernw)$) {};
}
\begin{document}
\tikzset{%
box/.style = {red, thick, rounded corners},
arrow/.style = {->, green, ultra thick},
}
\begin{tikzpicture}[node distance=0.1cm, auto]
% image
\node[anchor=south west,inner sep=0] (image) at (0,0) {%
\includegraphics[width=0.9\textwidth]{example-image}
};
% annotate
\begin{scope}[x={(image.south east)},y={(image.north west)}]
\boxnode[draw=red,rounded corners]{box}{0.02,0.15}{0.1,0.9}
%\draw[box] (0.02,0.15) rectangle (0.1,0.9);
\draw[arrow] (box.north) -- ++(0,1cm) node[black,above]{Home};
\end{scope}
\end{tikzpicture}
\end{document}