在C#中维护质心的同时将N像素缓冲区添加到多边形(区域/路径)

时间:2013-12-03 17:05:02

标签: c# geometry system.drawing polygons scaletransform

问题:在保持多边形的质心的同时,将n像素缓冲区添加到现有多边形(保证为闭合,非重叠,以及顺时针形成点)。

当前:我有一个PolyRegion类,其中包含System.Drawing Path和System.Drawing Region。当我实例化类时,我会将因子缓冲区添加到路径中并对其进行缩放/转换。如果相对于质心缩放,则结果是偏移。

示例:绿色多边形是原始多边形。当我按n倍的比例缩放时,我得/想要紫色多边形(以质心为中心)。

enter image description here

问题:如何针对质心进行缩放? AM我最好缩放点阵列中的每个点或缩放路径/区域?

代码:

public PolyRegion(Int32 Id, List<Point> Points)
{
    this.Id = Id;
    this.Points = Points;
    this.Path = this.CreatePath();

    float factor = 10;
    float wScale = (float)((this.Path.GetBounds().Width - factor) / this.Path.GetBounds().Width);
    float hScale = (float)((this.Path.GetBounds().Height - factor) / this.Path.GetBounds().Height);
    Matrix transformMatrix = new Matrix();
    transformMatrix.Scale(wScale, hScale);
    this.Path.Transform(transformMatrix);

    this.Region = new Region(this.Path);
    this.Area = CalculateArea();  
}

2 个答案:

答案 0 :(得分:0)

这是一个数学/几何问题,而不是编程问题:

1)将图形从质心位置(x,y)转换为(0,0)坐标

2)按你想要的因素进行扩展。

3)翻译回原始质心。

答案 1 :(得分:0)

我决定抛弃矩阵和区域尺度并进行变换并采用更纯粹的方法。

首先我计算出polgon的质心:

private Point GetCentroid()
{
int centroidX = 0;
int centroidY = 0;
int pointCount = this.Points.Count();

for (int i = 0; i < pointCount; i++)
{
centroidX = centroidX + this.Points[i].X;
centroidY = centroidY + this.Points[i].Y;
}

centroidX = centroidX / pointCount;
centroidY = centroidY / pointCount;

return new Point(centroidX, centroidY);
}

然后遍历每个点并用S和T缓冲它(我的缓冲因子):

private List<Point> GetBufferedPoints()
{
int c = this.Centroid.X;
int d = this.Centroid.Y;
int s = this.BufferFactor;
int t = this.BufferFactor;
int pointCount = this.Points.Count();
PointsBuffered = new List<Point>();

for (int i = 0; i < pointCount; i++)
{
int x = this.Points[i].X;
int y = this.Points[i].Y;
PointsBuffered.Add(new Point((s * (x - c)) + c, (t * (y - d)) + d));
}

return PointsBuffered;
}

结果:

enter image description here