如何使用距离公式用纯色填充圆圈?

时间:2019-10-17 23:09:46

标签: c++

我是c ++的初学者,在运行代码时编写了一个for循环来显示空心圆,但是,我想知道如何使用距离公式(d = sqrt(( ax-bx)^ 2 +(ay-by)^ 2)。这是我到目前为止所拥有的!任何帮助将不胜感激!

enter image description here

int MAX = 728;
for (float t = 0; t < 2 * 3.14; t += 0.01)
    SetPixel(MAX / 4 + MAX / 6 * sin(t), MAX / 4 + MAX / 6 * cos(t), 255, 255, 0);

3 个答案:

答案 0 :(得分:1)

Pffff ...不要使用sin和cos!而是使用sqrt(1-x ^ 2)方法。您可以查看在Google中渲染圆圈的公式,例如:https://www.google.com/search?q=sqrt(1-x^2)

我编辑此答案,因为似乎不清楚:

float radius = 50.0f;
for (int x = -radius; x <= radius; ++x) {
    int d = round(sqrt(1.0f - (x * x / radius / radius)) * radius); 
    for (int y = -d; y <= d; ++y) {
        SetPixel(x, y, 255, 255, 0);
    }
}

注意:每个图形库都不同,因此我假设您正确使用了“ SetPixel”功能。

现在,对于大多数人来说,使用sqrt(1-x ^ 2)方法就足够了,但是似乎有些拒绝投票的人并不认为相同的XD。

答案 1 :(得分:1)

效率低下,可能是您真正想画圆的最后一种方法...但是...

在围绕圆的整个正方形上,计算每个像素距中心的距离,并设置半径是否小于或等于半径。

// Draw a circle centered at (Xcenter,Ycenter) with given radius using distance formula

void drawCircle(HDC dc, int XCenter, int YCenter, int radius, COLORREF c) {
    double fRad = radius * 1.0; // Just a shortcut to avoid thrashing data types

    for (int x = XCenter - radius; x<XCenter + radius; x++) {
        for (int y = YCenter - radius; y<YCenter + radius; y++) {
            double d = sqrt(((x - XCenter) * (x - XCenter)) + ((y - YCenter) * (y - YCenter)) );
            if (d <= fRad) SetPixel(dc, x, y, c);
        }
    }
}

注意事项:不再警告,使用C ++环境并对此进行测试。 :-)

致电:

int main()
{
    HWND consoleWindow = GetConsoleWindow();
    HDC consoleDC = GetDC(consoleWindow);

    drawCircle(consoleDC, 50, 50, 20, RGB(255, 0, 255));

    ReleaseDC(consoleWindow, consoleDC);
    return 0;
}

答案 2 :(得分:1)

#include <windows.h>
#include <iostream>

using namespace std;

int main()
{
    HWND consoleWindow = GetConsoleWindow(); // Get a console handle
    HDC consoleDC = GetDC(consoleWindow);    // Get a handle to device context

    int max = 628;
    float i = 0;
    float t;
    float doublePi = 6.29;

    for (i = 0.0; i < max; i += 2.0) {
        for (t = 0.0; t < doublePi; t += 0.01) {
            SetPixel(consoleDC, max / 4 + (max - i) / 6 * sin(t), max / 4 + (max - i) / 6 * cos(t), RGB(255, 255, 0));
        }
    }

    ReleaseDC(consoleWindow, consoleDC);
    cin.ignore();

    return 0;
}

运作良好。绘制并填写!有点慢...