从一侧缩放多边形

时间:2016-01-11 15:32:27

标签: c# algorithm math

我想让Polygon(Rectangle)更小,我写这个函数可以很好地减少四边形的矩形但是当我想从矩形的一边做小矩形时我得到了Nan值。

enter image description here

float accuracy =0.95f;
PointF pCenter = new PointF();
PointF[] lot = new PointF[4];
lot[0] = new PointF(4.6f,8.9f);
lot[1] = new PointF(4.6f, 3.2f);
lot[2] = new PointF(1.209f, 3.2f);
lot[3] = new PointF(1.209f, 8.92f);
pCenter.X = (lot[0].X + lot[1].X) / 2;
pCenter.Y = (lot[0].Y + lot[1].Y) / 2;
//IF I write This it Works Fine
//pCenter.X = (lot[0].X + lot[1].X+ lot[2].X+ lot[3].X) / 4;
//pCenter.Y = (lot[0].Y + lot[1].Y+ lot[2].Y+ lot[3].Y) / 4;
float dx;
float dy;
for (int ii = 0; ii < 4; ii++)
{
    var p = lot[ii];
    dx = p.X - pCenter.X;
    dy = p.Y - pCenter.Y;
    float add = dx * accuracy;
    float x = pCenter.X + add;
    float y = pCenter.Y + dy * (x - pCenter.X) / dx;
    lot[ii] = new PointF(x, y);
}

1 个答案:

答案 0 :(得分:2)

要按照建议缩放矩形,不需要循环。也没有必要计算中心。例如,您可以使用以下功能。我按照与你相同的顺序列举了矩形的点(p0,p1,p2和p3):

private void scaleRectangle(Rectangle r, float scale) {

    float width = r.p1.X - r.p2.X;

    r.p2.X = r.p1.X - width * scale;
    r.p3.X = r.p0.X - width * scale;
}