2012-11-12 56 views
4

我有一些代碼whiсh產生矩形wшth任意角度:剪輯矩形用C#

enter image description here

但我需要切割的孩子由家長邊框的矩形,如

enter image description here

我的代碼: http://pastebin.com/b6ry8j68

任何人都可以幫我算法嗎?

+0

max和min,x和y。 –

+0

你是什麼意思? – Wolfgang

+0

如何確定矩形的父/子關係? –

回答

3

使用SetClip屬性很容易。

基本上你需要添加以下代碼:DrawLine的命令前右

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

。其中x和y是您父矩形的座標。這很容易從你的功能中獲得。

這是工作的全功能:

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]); 
    } 

編輯:
這不是一個完整的例子,因爲這一個將只設置夾於母公司的寬度和高度。你需要修改你的函數來提供每個元素的寬度和高度。但現在我正在看你提供的圖片,它看起來比我想象的更復雜。
您可能最終將存儲所有隨機值的數組,並按大小排序,然後繪製所有元素。

+0

是的,這是真的有用,但它是大學的任務,我認爲我必須讓沒有任何幫助者像setClip – Wolfgang

+0

實現這樣一個很好的答案。經常遇到這個問題。 – Neophile