c++ - (C++) 夹持圆内二维位置(使用中点圆算法绘制)

标签 c++ geometry trigonometry angle clamp

我目前正在我的 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;
    }
}

关于c++ - (C++) 夹持圆内二维位置(使用中点圆算法绘制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47175118/

相关文章:

c++ - 使用 xerces 读取 C++ 中的属性名称

javascript - 万有引力计算

c++ - 使用 wkhtmltopdf C 库将本地 HTML 文件转换为 PDF

c++ - Qt iOS 问题 - 使用 QAudioRecorder 更改音频输出设备

python - 霍夫圆变换为圆形阴影

math - 在给定点的坐标的情况下,如何在二维空间中找到这些点的方向?

c# - 将对角线延长一个值

c++ - Matlab三角函数

java - 播放不同音高的正弦波

c++ - 在可变参数模板函数中同时接受 int 和 class?