C# - How to get the area of a System.Drawing.Region?

房东的猫 提交于 2021-01-29 03:51:12

问题


I'm computing the area of a rectagle after exclude the area of some circles. this is my current solution:

    var region = new Region( new Rectangle(0, 0, 10, 10) );
    var circle = new System.Drawing.Drawing2D.GraphicsPath();
    circle.AddEllipse(50, 50, 25, 25);
    // Exclude the circle from the region.
    region.Exclude(circle);

However I need something like region.getArea() to get the area after excluding the circle.

Do you know how to compute a System.Drawing.Region area?

-Or-

Do you know another way to compute a rectangle area after excluding some circles?


回答1:


        float diam = 25;
        var region = new Region(new RectangleF(0, 0, diam, diam));
        var circle = new System.Drawing.Drawing2D.GraphicsPath();
        circle.AddEllipse(0, 0, diam, diam);
        region.Exclude(circle);

        var rects = region.GetRegionScans(new System.Drawing.Drawing2D.Matrix());
        float area = 0;
        foreach (var rc in rects) area += rc.Width * rc.Height;
        double realArea = diam * diam - Math.PI * diam * diam / 4;
        Console.WriteLine("Approx area = {0}, real area = {1}", area, realArea);

Output: Approx area = 141, real area = 134.126147876595

Keep this result in mind, the Region class was designed to be used in graphic code. It is only accurate to a pixel with a knack for rounding errors to accumulate. The larger you make diam, the smaller the relative error.




回答2:


Theres no method to do so, but my best guess is that the GetRegionData function will give you back a RegionData who's Data member is a byte[] which matches the RGNDATA stucture from C++. In there you have a header with a list of rectangles which don't overlap. Calculating the area would be a simple for-loop at that point.

If the area is all your interested in and you don't plan to use the Region for drawing then this is probably an overkill. The code my be simple but you'll be using up more memory and computer resources for a value calculation.

Solving it the 'mathy' way might involve alot of special cases, but once you solve the line-circle intersection code it shouldn't be too bad and would probably be faster than all the memory allocation of a RegionData and DC context.



来源:https://stackoverflow.com/questions/4418426/c-sharp-how-to-get-the-area-of-a-system-drawing-region

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!