How could I fill in my circle with a solid color using the distance formula?

Viewed 190

I am a beginner in c++ and have coded a for loop to show a hollow circle when I run the code, however, I was wondering how I could achieve a filled-in circle using the distance formula (d = sqrt((ax-bx)^2 + (ay-by)^2). Here's what I have so far! Any help would be appreciated!

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 Answers

Pffff... do not use sin and cos! instead use the sqrt(1-x^2) approach. You can view the formula rendering a circle in google for example: https://www.google.com/search?q=sqrt(1-x^2)

I edit this answer because it seems that is not clear:

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

Note: each graphic library is different, so I assumed that you used rightfully the "SetPixel" function.

Now, for most people say the sqrt(1-x^2) approach should be enough, but it seem that some downvoters does not think the same XD.

Inefficient as can be, and probably the last way you really want to draw a circle ... but ...

Over the entire square encompassing your circle, calculate each pixel's distance from the center and set if under or equal the radius.

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

Caveat: No more caveat, used a C++ environment and tested it this time. :-)

Call thusly:

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

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

    ReleaseDC(consoleWindow, consoleDC);
    return 0;
}
#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;
}

Working almost well. Draw and fill in! A little slow...

Related