关于数学:基于两个点画一个圆

Draw a circle based on two points

我的坐标有两个点,必须画一个圆。 一个点是圆心,另一点是圆的边缘,因此,两点之间的距离基本上是圆的半径。 我必须在MFC中执行此操作。 我试过了,但是圆圈绘制不正确。 通常,它比应该的要大。

1
2
3
4
5
6
7
double radius = sqrt((c->p1.x*1.0 - c->p1.y) * (c->p1.x - c->p1.y) +
                     (c->p2.x - c->p2.y) * (c->p2.x - c->p2.y));

CPen black(PS_SOLID,3,RGB(255,0,0));
pDC->SelectObject(&black);

pDC->Ellipse(c->p1.x-radius , c->p1.y-radius, c->p1.x+radius, c->p1.y+radius);

p1p2是点。 圆被绘制为矩形的圆形。 Ellipse()中的参数是矩形的左上角和右下角。


这是一个计算半径的实现,更易于阅读(更正):

1
2
3
4
5
6
7
8
9
10
11
#include <cmath>

int findRadius( const CPoint& p1, const CPoint& p2 ) {
    // Calculate distance
    CPoint dist{ p2 };
    dist -= p1;
    // Calculate radius
    double r = std::sqrt( ( dist.x * dist.x ) + ( dist.y * dist.y ) );
    // Convert to integer with appropriate rounding
    return static_cast<int>( r + 0.5 );
}

您可以从渲染代码中使用它:

1
2
3
4
5
6
7
8
int radius = findRadius( c->p1, c->p2 );
CPen black( PS_SOLID, 3, RGB( 255, 0, 0 ) );
// Save previously selected pen
CPen* pOld = pDC->SelectObject( &black );
pDC->Ellipse( c->p1.x - radius, c->p1.y - radius,
              c->p1.x + radius, c->p1.y + radius );
// Restore DC by selecting the old pen
pDC->SelectObject( pOld );

您的半径计算错误……应该是:

1
2
double radius = sqrt(((c->p2.x - c->p1.x)*(c->p2.x - c->p1.x))
                    +((c->p2.y - c->p1.y)*(c->p2.y - c->p1.y)));