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

问题描述 投票:1回答:3

我是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);
c++
3个回答
1
投票

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

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

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

void drawCircle(int Xcenter, int Ycenter, int radius) {
   float 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++) {
         float d = sqrt((x-Xcenter)^2 + (y-Ycenter)^2);
         if ( d <= fRad ) SetPixel(x, y);
      }
   }
}


0
投票

您必须获取HDC并将其作为第一个参数传递。

声明:

HWND consoleWindow = GetConsoleWindow();

获取控制台句柄。之后:

HDC consoleDC = GetDC(consoleWindow);

获取设备上下文的句柄。

最后,在setPixel函数中:

SetPixel(consoleDC, max / 4 + max / 6 * sin(t), max / 4 + max / 6 * cos(t), RGB(255, 255, 0));

然后将绘制黄色圆圈!


0
投票

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。

© www.soinside.com 2019 - 2024. All rights reserved.