c# - 用c#裁剪矩形

标签 c# graphics rectangles clip

我有一些代码可以生成具有随机角度的矩形:

enter image description here

但我需要通过父边框切割子矩形,例如

enter image description here

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

谁能帮我做算法?

最佳答案

SetClip 很容易做到属性(property)。

基本上你需要添加这段代码:

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

编辑:
这不是一个完整的例子,因为这个例子只会将 Clip 设置为父宽度和高度。您需要修改函数以提供每个元素的宽度和高度。但是现在我在看你提供的图片,它看起来比我想象的要复杂。
您可能最终会存储所有随机值的数组,并按大小对其进行排序,然后绘制所有元素。

关于c# - 用c#裁剪矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13339186/

相关文章:

opengl - 使用 OpenGL 在 vram 中存储三角形纹理

javascript - 找到面积最大的元素(主要内容区域)?

javascript - jQuery 或 javascript 中是否有 'if (!Page.IsPostBack)' 之类的东西?

graphics - block 压缩图像如何始终具有 4 倍数的第一个 mip 级别?

c# - .NET中的内存管理

Java AWT - 绘制由平滑曲线连接的多边形

java - 矩形不动

image - 如何找到检测到的 Blob /对象重叠以及如何将其分组?

c# - 当 T 是对象的后代时,为什么不能将 Predicate<T> 分配给 Predicate<object>?

C# Linq to Entities : The type of one of the expressions in the join clause is incorrect. 类型推断失败