C#-如何获取System.Drawing.Region的区域? [英] C# - How to get the area of a System.Drawing.Region?
问题描述
在排除一些圆的面积之后,我正在计算矩形的面积.这是我目前的解决方案:
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);
但是我需要诸如region.getArea()之类的东西才能在排除圆后获取面积.
However I need something like region.getArea() to get the area after excluding the circle.
您知道如何计算System.Drawing.Region区域吗?
-或-
在排除某些圆之后,您知道另一种计算矩形面积的方法吗?
推荐答案
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);
输出:大约面积= 141,实际面积= 134.126147876595
Output: Approx area = 141, real area = 134.126147876595
请记住此结果,Region类旨在用于图形代码.它仅对具有诀窍的像素准确,以便累积舍入误差. diam 越大,相对误差越小.
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.
这篇关于C#-如何获取System.Drawing.Region的区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!