(C++)在圆内夹紧 2D 位置(使用中点圆算法绘制)

(C++) Clamp 2D Position Within Circle (Drawn Using Midpoint Circle Algorithm)

本文关键字:绘制 算法 C++ 2D 位置      更新时间:2023-10-16

我目前正在C++程序中使用中点圆算法绘制圆圈。这是我正在使用的代码的示例。

void drawcircle(int x0, int y0, int radius)
{
    int x = radius-1;
    int y = 0;
    int dx = 1;
    int dy = 1;
    int err = dx - (radius << 1);
    while (x >= y)
    {
        putpixel(x0 + x, y0 + y);
        putpixel(x0 + y, y0 + x);
        putpixel(x0 - y, y0 + x);
        putpixel(x0 - x, y0 + y);
        putpixel(x0 - x, y0 - y);
        putpixel(x0 - y, y0 - x);
        putpixel(x0 + y, y0 - x);
        putpixel(x0 + x, y0 - y);
        if (err <= 0)
        {
            y++;
            err += dy;
            dy += 2;
        }
        if (err > 0)
        {
            x--;
            dx += 2;
            err += (-radius << 1) + dx;
        }
    }
}

现在,我的问题是,如果我像drawcircle(100, 100, 100);这样画一个圆,我怎么能采取 2D 位置并检查该 2D 位置是否在圆内,如果没有,则在圆的边缘返回一个"夹紧"的 2D 位置。

这应该有助于解释我试图更好地完成什么。

void _2DPostionToCirclePosition(Vector2D in, Vector2D *out)
{
    //assume in = Vector2D(800, 1100)
    //here we somehow calculate if the in 2D
    //position is within the circle we
    //are drawing drawcircle(100, 100, 100).
    //if the in 2D vector is within the circle
    //just return in. but if it outside of the
    //circle calculate and return a clamped position
    //to the edge of the circle
    (*out).x = calculatedOutX;
    (*out).y = calculatedOutY;
}

要首先确定一个点是否在圆中,您需要计算它与圆心的距离,这里有 (100,100)。像这样:

#include <math.h> //for pow and sqrt
double getPointDistance(int x, int y) {
    return sqrt (pow ((circleCenterX - x), 2.0) + 
        pow ((circleCenterY - y), 2.0));
}

然后你可以把它和你的圆半径进行比较,如果距离大于半径,它在外面,如果它更小,它在里面,如果它相等,那么它就在边缘。为此,您可以使用这样的东西:

bool isInCircle(int x, int y) {
    if (circleRadius >= getPointDistance(x, y)) {
        //it's inside the circle (we assumed on the edge is inside)
        return true;
    } else {
        //given point is outside of the circle
        return false;
    }
}