如何控制这个foreach产生的node内容限定在框内?

发布于 2025-04-08 22:39:35

image.png

取消ifnum这三行注释后,会报错;
保持注释时,在PDF中存在透明的node内容,若复制,会得到隐藏的node内容。
我想TeX不输出框外的那几个坐标,而不仅是隐藏它!
这样在选择复制的时候就不会得到隐藏的node内容。
主要是不会写判断条件,恳请大佬指点!

\documentclass[border=2pt,tikz]{standalone}
\begin{document}
\begin{tikzpicture}
    \foreach \x in {1,2}
    \foreach \y in {1,...,6}
        \node at (\x-.5,\y-.5) [scale=.75] {$(\x,\y)$};

    \draw (0,0) grid ([xshift=-.01pt]2,6);
    \clip [xshift={2cm-.01pt}] (0,0) -- (45:{3*sqrt(2)}) -- (90:6) -- cycle;
    \draw [xshift=2cm,rotate=45,step={sqrt(2)/2}] (0,0) grid (6,6);

    \foreach \x in {2.5,3.5,4.5}
    \foreach \y in {1,...,5}
        \node at (\x,\y) [scale=.5] {$(\x,\y)$};
    \foreach \x in {3,4}
    \foreach \y in {1.5,2.5,3.5,4.5} {
        \node at (\x,\y) [scale=.5,text=red] {$(\x,\y)$};
%        \ifnum \x+\y<8 and \x-\y<2 \relax
%        \breakforeach
%        \fi
    }
\end{tikzpicture}
\end{document}

查看更多

关注者
1
被浏览
170
1 个回答
Sagittarius Rover
我要成为Typst糕手/(ㄒoㄒ)/~~

这种形如方程x+y=const的映射必定是线性的,所以找到一个用两重循环的变量\x以及\y正好可以覆盖所需位置的线性坐标映射即可:

\documentclass[border=2pt,tikz]{standalone}
\begin{document}
\begin{tikzpicture}
    \foreach \x in {1,2}
        \foreach \y in {1,...,6}
            \node at (\x-.5,\y-.5) [scale=.75] {$(\x,\y)$};
        \draw (0,0) grid ([xshift=-.01pt]2,6);
        \clip [xshift={2cm-.01pt}] (0,0) -- (45:{3*sqrt(2)}) -- (90:6) -- cycle;
        \draw [xshift=2cm,rotate=45,step={sqrt(2)/2}] (0,0) grid (6,6);
        \foreach \x in {5,...,9}
            \foreach \y in {1,...,\fpeval{(10-\x)}}
                \node at (\x/2,\fpeval{\y+(\x-5)/2}) [scale=.5] {$(\fpeval{\x/2},\fpeval{\y+(\x-5)/2})$};
\end{tikzpicture}
\end{document}

image.png

Edited:

其实也就是小学生找规律问题的\pgffor版本罢了...

General Case:

\documentclass[border=2pt,tikz]{standalone}
\newcommand*{\drawmygrid}[2]{%
    \begin{tikzpicture}
    \foreach \x in {1,...,#1}
        \foreach \y in {1,...,#2}
            \node at (\x-.5,\y-.5) [scale=.75] {$(\x,\y)$};
        \draw (0,0) grid ([xshift=-.01pt]#1,#2);
        \clip [xshift={#1cm-.01pt}] (0,0) -- (45:{(#2/2)*sqrt(2)}) -- (90:#2) -- cycle;
        \draw [xshift={#1cm},rotate=45,step={sqrt(2)/2}] (0,0) grid (#2,#2);
        \def\Na{\fpeval{2*#1+1}}
        \def\Nb{\fpeval{\Na+#2-1}}
        \foreach \x in {\Na,...,\fpeval{\Nb-1}}
            \foreach \y in {1,...,\fpeval{\Nb-\x}}
                \node at (\x/2,\fpeval{\y+(\x-\Na)/2}) [scale=.5] {$(\fpeval{\x/2},\fpeval{\y+(\x-\Na)/2})$};
\end{tikzpicture}
}
\begin{document}
\drawmygrid{2}{6}

\drawmygrid{5}{10}

\drawmygrid{8}{15}
\end{document}

image.png

撰写答案

请登录后再发布答案,点击登录

发布
问题

分享
好友

手机
浏览

扫码手机浏览