(C++)在圆内夹紧 2D 位置(使用中点圆算法绘制)
(C++) Clamp 2D Position Within Circle (Drawn Using Midpoint Circle Algorithm)
我目前正在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;
}
}
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- QuadTree只在窗口的右上角绘制
- 绘制旋转的三角形
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 绘制线条的最佳算法
- OpenGL:布雷森汉姆的线条绘制算法实现
- 使用四边形绘制球体的算法
- (C++)在圆内夹紧 2D 位置(使用中点圆算法绘制)
- 通过按住 Shift 按钮绘制直线的算法
- 算法绘制图形
- c++ 布雷森汉姆的线算法绘制弧形和旋转
- OpenCV绘制一个椭圆从camshift算法输出
- 线条绘制算法的实现无法正常工作
- visual studio 2010 -中点算法在绘制线条c++
- 为什么这个中点线算法不绘制垂直线(或接近垂直线的对角线)?