2d coordinates expansion and shrinking

Viewed 192

I was trying to expand or shrink the 2d object up to K. Let's say I've a co-ordinate system like { {5,0}, {0,0}, {0,-5}, {5,-5}, {5,-10}, {0,-10} } (yellow marker shape) and I want to offset every position K = 1. The resultant shape would look something like this

Open shape Polygon

As my initial approach was to find the center of the shape and increase each coordinate according to the center, the source is here. But it seems like it only works on a closed symmetric shape like squares and for asymmetric shapes or open shapes, it doesn't work.

My code is given below

void myFun() {
        std::vector<std::pair<double, double>> co, CO;
        co = { { {5,0}, {0,0}, {0,-5}, {5,-5}, {5,-10}, {0,-10} } };
        double x = 0, y = 0;
        double n = co.size();
        for (auto it : co) {
            x += it.first; y += it.second;
        }
        std::pair<double, double> o = { x / n, y / n };
        int K = 1;
        for (auto it : co) {
            std::pair<double, double> inc = { (it.first - o.first) * K, (it.second - o.second) * K };
            CO.push_back({ o.first - inc.first, o.second - inc.second });
        }
        reverse(CO.begin(), CO.end());
        for (auto it: CO) {}
    }

The output co-ordinate shape is

enter image description here

How can I improve my approach and solve this issue? Thank you.

1 Answers

I see two ways for you to achieve what you are after:

  1. simply scaling around a point. Take all the coordinates that make up the shape and scale them. To make that happen around a certain point, use the usual approach consisting of those steps: 1. Translate such that (0,0) is the point to scale around, 2, Scale and 3. Translate back. That can easily be done with transform matrices.

  2. Offset each point. That is far more complicated, since it requires you to define an In- / Outside of the shape. Event though this is a description for bezier curves, here you can find a good and illustrative description of the approach. Basically you need to find some kind of normal vector for each Point in the shape and offset it on a fixed amount in that direction.

Maybe there are other way and combinations of the both above which finally snap each point on the grid by rounding.

Related