我知道我可以使用 tikz 绘制一个矩形\draw (0.0,0.0) rectangle (1.0,1.0);
。是否有可能直接从形状确定所有 4 个边缘坐标?
我确实可以通过 保存左下角坐标和右上角\draw (0.0,0.0) coordinate (lb) rectangle (1.0,1.0) coordinate (ru);
。但是有没有办法直接从形状中获取左上角和右下角?
我知道我可以计算它们。但是它们能直接从形状中访问吗?
平均能量损失
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
% the rectangle
\draw (0.0,0.0) coordinate (lb) rectangle (1.0,1.0) coordinate (ru);
% coordinates
\draw (lb) circle [radius=2pt];
\draw (ru) circle [radius=2pt];
% calculated coordinates
\draw[dashed] (lb |- ru) coordinate (lu) circle [radius=2pt];
\draw[dashed] (lb -| ru) coordinate (rb) circle [radius=2pt];
\end{tikzpicture}
\end{document}
答案1
你可以定义自己的矩形路径。在 MWE 中
\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}[my rectangle/.style={to path={
-| coordinate[pos=0.5] (#1-2) (\tikztotarget) coordinate (#1-3)
-| coordinate (#1-4) (\tikztostart) coordinate (#1-1) }}]
\draw (0,0) edge[my rectangle=krtek] (1,1);
\foreach \X in {1,...,4}
{\draw (krtek-\X) circle [radius=2pt];}
\end{tikzpicture}
\end{document}
风格my rectangle=<coordinate base name>
将为四个角赋予名称coordinate base name-1
,...,coordinate base name-4
。
当然,还存在预定义的形状,其角坐标存储在锚点中。
\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\usetikzlibrary{shapes.geometric}
\begin{tikzpicture}
% the rectangle
\path (0,0) node[draw,anchor=south west,minimum size=1cm] (R) {};
\foreach \X in {45,135,225,315}
{\draw (R.\X) circle [radius=2pt];}
\path (2,0) node[draw,anchor=south west,minimum size={sqrt(2)*1cm},regular polygon,regular
polygon sides=4] (poly) {};
\foreach \X in {1,...,4}
{\draw (poly.corner \X) circle [radius=2pt];}
\end{tikzpicture}
\end{document}
答案2
如果您不想明确声明角的坐标,您可以自动将矩形转换为node
带有fit
库的矩形。这样,生成的节点会为您提供所有矩形锚点,而无需命名它们。
以下示例显示如何将矩形坐标插入fit
参数。结果节点相当于之前绘制的矩形(您不需要绘制之前的矩形,这只是为了演示目的)。
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{fit}
\begin{document}
\begin{tikzpicture}
\draw (0,0) rectangle (2,1);
\node[fit={(0,0) (2,1)}, inner sep=0pt, draw=red, opacity=.5] (a) {};
\foreach \i in {north east, north west, south east, south west}
\draw (a.\i) circle(2pt);
\end{tikzpicture}
\end{document}