我有一张像这样的 tikz 图片(一个简单的字符串图)
\begin{tikzpicture}[x=0.5cm, y=0.3cm]
\draw (0,0) -- (1,0);
\draw[rounded corners=0.3cm] (1,0) -- (1,1) -- (2,1);
\draw[rounded corners=0.3cm] (1,0) -- (1,-1) -- (2,-1);
\draw[fill=white] (1,0) circle (1.75pt);
\end{tikzpicture}
我会制作更多这样的,以后我可能会更改 y 轴的比例。如果我这样做,我希望圆角也能缩放。换句话说,除了写 ,rounded corners=0.3cm
有没有办法指定舍入应该是“一个 y 单位”?
当然,我可以只定义一个 y 长度的宏,但我想知道是否有更惯用的方法。我想更普遍的问题是如何尽可能避免 tikz 图中出现魔法数字。
答案1
一个解决方案是使用这种技术Paul Gaborit 表示:
\documentclass[tikz, border=2mm]{standalone}
\usetikzlibrary{calc}
\newcommand*{\getylength}[1]{
\path let \p{y}=(0,1), \n{ylen}={veclen(\x{y},\y{y})}
in \pgfextra{\xdef#1{\n{ylen}}};
}
\begin{document}
\begin{tikzpicture}[x=0.5cm, y=0.3cm]
\getylength{\myylen}
\draw (0,0) -- (1,0);
\begin{scope}[rounded corners=\myylen]
\draw (1,0) -- (1, 1) -- (2, 1);
\draw (1,0) -- (1,-1) -- (2,-1);
\end{scope}
\draw[fill=white] (1,0) circle[radius=1.75pt];
\end{tikzpicture}
\end{document}
利用[x=1.0cm, y=0.6cm]
可得:
答案2
你也可以定义一个函数,tikzy
告诉你当前的y
值是多少。然后你可以这样写:
\draw[rounded corners=tikzy] (1,0) -- (1,1) -- (2,1);
还要注意,如果您确实想要生成许多这样的文件,您可能需要使用pic
。
\documentclass[tikz,border=3mm]{standalone}
\makeatletter
\pgfmathdeclarefunction{tikzy}{0}{\begingroup
\edef\pgfmathresult{\the\pgf@yy}%
\pgfmathsmuggle\pgfmathresult
\endgroup}
\makeatother
\begin{document}
\begin{tikzpicture}[pics/semiarc/.style={code={ \draw (0,0) -- (1,0);
\draw[rounded corners=tikzy] (1,0) -- (1,1) -- (2,1);
\draw[rounded corners=tikzy] (1,0) -- (1,-1) -- (2,-1);
\draw[fill=white] (1,0) circle[radius=1.75pt];}}]
\begin{scope}[x=0.5cm, y=0.3cm]
\draw (0,0) -- (1,0);
\draw[rounded corners=0.3cm] (1,0) -- (1,1) -- (2,1);
\draw[rounded corners=0.3cm] (1,0) -- (1,-1) -- (2,-1);
\draw[fill=white] (1,0) circle[radius=1.75pt];
\end{scope}
\begin{scope}[xshift=2cm,x=0.5cm, y=0.3cm]
\draw (0,0) -- (1,0);
\draw[rounded corners=tikzy] (1,0) -- (1,1) -- (2,1);
\draw[rounded corners=tikzy] (1,0) -- (1,-1) -- (2,-1);
\draw[fill=white] (1,0) circle[radius=1.75pt];
\end{scope}
\begin{scope}[xshift=4cm,x=0.8cm, y=0.6cm]
\draw (0,0) -- (1,0);
\draw[rounded corners=tikzy] (1,0) -- (1,1) -- (2,1);
\draw[rounded corners=tikzy] (1,0) -- (1,-1) -- (2,-1);
\draw[fill=white] (1,0) circle[radius=1.75pt];
\end{scope}
\begin{scope}[yshift=-2cm]
\pic[x=0.5cm, y=0.3cm]{semiarc};
\begin{scope}[xshift=2cm,x=0.5cm, y=0.3cm]
\pic{semiarc};
\end{scope}
\begin{scope}[xshift=4cm,x=0.8cm, y=0.6cm]
\pic{semiarc};
\end{scope}
\end{scope}
\end{tikzpicture}
\end{document}