根据两点画圆

Draw a circle based on two points

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

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() 中的参数是矩形的左上角和右下角。

你的半径计算有误...应该是:

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)));

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

#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 );
}

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

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 );