根据两点画一个圆

时间:2017-03-01 16:47:46

标签: math mfc geometry 2d

我的坐标有两个点,必须画一个圆圈。一个点是中心,另一个点是圆的边缘,所以基本上两点之间的距离是圆的半径。我必须在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()中的参数是矩形的左上角和右下角。

2 个答案:

答案 0 :(得分: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)));

答案 1 :(得分:2)

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

#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 );
相关问题