Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clipping rectangle with c#

I have some code whiсh generate rectangles wшth random angle:

enter image description here

But i need cut children rectangle by parent border, e.g

enter image description here

My code: http://pastebin.com/b6ry8j68

Can anyone help me with algo?

like image 853
Wolfgang Avatar asked Nov 12 '12 06:11

Wolfgang


1 Answers

It's pretty easy to do with SetClip Property.

basically you need to add this code:

           if (!pre_defined)
            {
                g.SetClip(new Rectangle(x, y, 600, 300));
            }

right before drawline commands. where x and y are coordinates of your parent rectangular. which is easy to get from your function.

this is 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;
        //top left
        P[0] = new PointF((float)Math.Round(x + (Width / 2) * Math.Cos(A) + (Height / 2) * Math.Sin(A)), (float)Math.Round(y - (Height / 2) * Math.Cos(A) + (Width / 2) * Math.Sin(A)));
        //top right
        P[1] = new PointF((float)Math.Round(x - (Width / 2) * Math.Cos(A) + (Height / 2) * Math.Sin(A)), (float)Math.Round(y - (Height / 2) * Math.Cos(A) - (Width / 2) * Math.Sin(A)));
        //bottom left
        P[2] = new PointF((float)Math.Round(x + (Width / 2) * Math.Cos(A) - (Height / 2) * Math.Sin(A)), (float)Math.Round(y + (Height / 2) * Math.Cos(A) + (Width / 2) * Math.Sin(A)));
        //bottom right
        P[3] = new PointF((float)Math.Round(x - (Width / 2) * Math.Cos(A) - (Height / 2) * Math.Sin(A)), (float)Math.Round(y + (Height / 2) * Math.Cos(A) - (Width / 2) * Math.Sin(A)));
        if (!pre_defined)
        {
            g.SetClip(new Rectangle(50, 50, 600, 300));
        }
        g.DrawLine(myPen, P[0], P[1]);
        g.DrawLine(myPen, P[1], P[3]);
        g.DrawLine(myPen, P[3], P[2]);
        g.DrawLine(myPen, P[2], P[0]);
    }

EDIT:
this is not a complete example, since this one will only set Clip to parent width and height. You need to modify your function to provide width and height of each element. But now I'm looking at the picture you provided and it looks more complicated than I thought.
You will probably end up storing array of all random values and that ordering it by size and then drawing all of the elements.

like image 163
RAS Avatar answered Sep 30 '22 07:09

RAS