This is pretty easy to do with the SetClip property .
basically you need to add this code:
if (!pre_defined) { g.SetClip(new Rectangle(x, y, 600, 300)); }
right before the drawline commands. where x and y are the coordinates of your parent rectangle. which is easy to get from your function.
this is a complete function that works:
public void drawRectangle(double Width, double Height, int A, bool pre_defined) { Graphics g = pictureBox1.CreateGraphics(); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; System.Drawing.Brush brush = new System.Drawing.SolidBrush(Color.FromArgb(r.Next(0, 251), r.Next(0, 251), r.Next(0, 251))); Pen myPen = new Pen(brush, 2); myPen.Width = 2; int x = center.X; int y = center.Y;
EDIT:
this is not a complete example, since it will only set Clip to the parent width and height. You need to change your function to ensure the width and height of each element. But now I look at the photo you provided, and it looks more complicated than I thought.
You will probably be able to save an array of all the random values ββand arrange it by size, and then draw all the elements.
source share