我想制作一个 TikZ 宏,它可以:
- 有一个可选的坐标参数
- 将 X 放置在这些坐标的中心。
这可能吗?
这就是我手动将两个 X 放在 10x10 网格上的方法。(当我要放置 40 个 X 并且它们全等但比 X 更复杂时,我需要一个宏。)
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw[gray] (-5,-5) grid (5,5);
\draw[line width =2pt] % x- and y-axes
(-5,0)--(5,0)
(0,-5)--(0,5);
\draw % Draws X as two paths, the way one normally would.
(1.5,4.5)--(0.5,3.5)
(0.5,4.5)--(1.5,3.5);
\draw % Draws the X as four "paths", all from the center of the X out.
(-3,2)--(-3.5,2.5)
(-3,2)--(-3.5,1.5)
(-3,2)--(-2.5,1.5)
(-3,2)--(-2.5,2.5);
\end{tikzpicture}
\end{document}
我该如何编写宏来避免自己必须写出这些 X 的路径?理想情况下,我想要这样的宏:
\newcommand{\X}
[1] % This optional argument would be the coordinates of the center of the X.
{whatever goes in here would use the coordinates above to draw the X}
\X{(3,-2)} % This would place the X at (3,-2).
我怎样才能让它工作?
答案1
您可以使用pic
路径并定义命令:
\documentclass{article}
\usepackage{tikz}
\tikzset{
myex/.pic = {
\draw
(-5mm,-5mm) -- (5mm,5mm)
(-5mm,5mm) -- (5mm,-5mm);
}
}
\newcommand\MyEx[1][(0,0)]{\pic at #1 {myex};}
\begin{document}
\begin{tikzpicture}
\draw[gray] (-5,-5) grid (5,5);
\draw[line width =2pt] % x- and y-axes
(-5,0)--(5,0)
(0,-5)--(0,5);
\pic at (3,3) {myex};
\MyEx
\MyEx[(3,-2)]
\MyEx[(-3,2)]
\end{tikzpicture}
\end{document}
在评论中提到,“X”的长度可能是指定为原点的坐标的函数;这里有一种使用库calc
和let
语法实现这一点的简单方法;“X”的长度等于作为“X”原点的向量的长度(可以实现更复杂的依赖关系,但我选择这个只是为了举例):
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\newcommand\MyEx[1][(0,0)]{
\draw
let
\p1=#1,
\n1={veclen(\p1)}
in
( $ #1 + (225:0.5*\n1) $ ) -- ( $ #1 + (45:0.5*\n1) $ )
( $ #1 + (135:0.5*\n1) $ ) -- ( $ #1 + (-45:0.5*\n1) $ );
}
\begin{document}
\begin{tikzpicture}
\draw[gray] (-5,-5) grid (5,5);
\draw[line width =2pt] % x- and y-axes
(-5,0)--(5,0)
(0,-5)--(0,5);
\MyEx
\MyEx[(0,3)]
\MyEx[(3.5,1.5)]
\MyEx[(1,1)]
\MyEx[(-1,-2)]
\MyEx[(-3,-1)]
\MyEx[(1,-3)]
\MyEx[(-3,3)]
\coordinate (aux) at (4,4);
\MyEx[(aux)]
\end{tikzpicture}
\end{document}
结果:
答案2
另一个解决方案是使用库cross out
中的有形状节点shapes.misc
。在下一个代码中,mycross
样式已经修复node contents={}
并使用at={#1}
选项来设置节点的中心坐标。并且,像往常一样,如果默认设置不喜欢,请根据特定需求进行更改。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes.misc}
\begin{document}
\begin{tikzpicture}[mycross/.style={cross out, draw,
inner sep=0pt, outer sep=0pt,
minimum size=1cm, node contents={}, at={#1}}]
\draw[gray] (-5,-5) grid (5,5);
\draw[line width =2pt] % x- and y-axes
(-5,0)--(5,0)
(0,-5)--(0,5);
\node[mycross={(2,4)}];
\node[mycross={(0,0)}];
\node[mycross={(-2,-3)}, minimum size=2cm, red, ultra thick];
\node[mycross={(1,-4)}, rotate=10];
\end{tikzpicture}
\end{document}