如何在指定的正方形/三角形区域内随机制作多个大小相似的圆圈?

如何在指定的正方形/三角形区域内随机制作多个大小相似的圆圈?

我想在指定的正方形区域或三角形区域内随机绘制多个圆。我尝试了一种由tikz:均匀随机分布圆圈正方形的起始点固定为 (0,0)。我根据自己的需求修改了它,但有一些错误。修改后的代码是

\documentclass[]{article}
\usepackage{tikz}
\usetikzlibrary{backgrounds}
\begin{document}
    % Here #1, #2 -- start of rectanle coordinates (x,y)
    % #3, #4 -- other end  of rectanle coordinates (x,y)
    %   #5, #6 -- circle radius and count(number) of circles.
    
    \def\xlist{6}
    \def\ylist{6}
    
    \newcommand{\fillrandomly}[6]{
        \pgfmathsetmacro\diameter{#3*2}
        \draw (#1,#2) rectangle (#3,#4);
        \foreach \i in {1,...,#6}{
            \pgfmathsetmacro\x{rnd*#3}
            \pgfmathsetmacro\y{rnd*#4}
            \xdef\collision{0}
            \foreach \element [count=\i] in \xlist{
                \pgfmathtruncatemacro\j{\i-1}
                \pgfmathsetmacro\checkdistance{ sqrt( ({\xlist}[\j]-(\x))^2 + ({\ylist}[\j]-(\y))^2 ) }
                \ifdim\checkdistance pt<\diameter pt
                \xdef\collision{1}
                \breakforeach
                \fi
            }
            \ifnum\collision=0
            \xdef\xlist{\xlist,\x}
            \xdef\ylist{\ylist,\y}
            \draw [black, fill=gray, thick] (\x,\y) circle [radius=#5];
            \fi 
            
        }
    }   
        
             \pgfmathsetseed{2}
         \fillrandomly{0.25}{2}{2}{4}{0.2}{200}
%%%%%%%%     
\end{tikzpicture}   
\end{figure}
\end{document}

这段代码有什么问题?这是我生成所需图像的糟糕代码

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{figure}[htbp]
    \centering
        %   \resizebox{0.98\textwidth}{!}{%
    \begin{tikzpicture} [every text node part/.style={align=center}, font=\scriptsize]
        \draw [->] (0,0) -- node[anchor=south] {x}  (4,0);
        \draw [->] (0,0) -- node[anchor = east] {y}  (0,4);
        \draw[ help lines,line width=0.005pt,step=0.5] (0,0) grid (4,4);

        \draw (0.25, 2) rectangle (2,4);
         \tikzset{my_circle/.style={circle, inner sep=0pt, minimum size=0.15cm, black,fill=gray, draw=none}};
        
         \node[my_circle] at (0.5,2. 3) {};
         \node[my_circle] at (0.8,2.3) {};
         \node[my_circle] at (1,2.5) {};
         \node[my_circle] at (1.4,3) {};
         \node[my_circle] at (1.5,3.5) {};
         \node[my_circle] at (1.5,3.8) {};
         \node[my_circle] at (1.8,3.7) {};
         \node[my_circle] at (1.5,3.5) {};
         \node[my_circle] at (1,3) {};
         \node[my_circle] at (0.6,3) {};
         \node[my_circle] at (0.4,3.5) {};
         \node[my_circle] at (1.8,2.6) {};
         \node[my_circle] at (1.5,2.2) {};
         \node[my_circle] at (0.8,3.8) {};
    \end{tikzpicture}
\end{figure}
\end{document}

相关内容