gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:07:44 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com