Drawing a Circle with Mid – Point Circle Algorithm in C/C++
As in the previous line drawing algorithm, we sample at unit intervals and determine the closest pixel position to the specified circle path at each step. For a given radius r and screen center position (xc, yc), we can first set up our algorithm to calculate pixel positions around a circle path centered at the coordinate origin (0, 0). Then each calculated position (x, y) is moved to its proper screen position by adding xc to x and yc to y. Along the circle section from x = 0 to x = y in the first quadrant, the slope of the curve varies from 0 to –1. Therefore, we can take unit steps in the positive x direction over this octant and use a decision parameter to determine which of the two possible y positions is closer to the circle path at each step. Position in the other seven octants are then obtained by symmetry.
The following section implements Mid – Point Circle Algorithm in C/C++. The source code is compiled using gcc Compiler and Code::Blocks IDE. To print a pixel, SetPixel() function of windows.h is used.
Note: to run this code in your machine with Code::blocks IDE, add a link library libgdi32.a (it is usually inside MinGWlib ) in linker setting.
Souce Code
Loading…
#include#include #define ROUND(a) ((int) (a + 0.5)) /* set window handle */ static HWND sHwnd; static COLORREF redColor=RGB(255,0,0); static COLORREF blueColor=RGB(0,0,255); static COLORREF greenColor=RGB(0,255,0); void SetWindowHandle(HWND hwnd){ sHwnd=hwnd; } /* SetPixel */ void setPixel(int x,int y,COLORREF& color=redColor){ if(sHwnd==NULL){ MessageBox(NULL,"sHwnd was not initialized !","Error",MB_OK|MB_ICONERROR); exit(0); } HDC hdc=GetDC(sHwnd); SetPixel(hdc,x,y,color); ReleaseDC(sHwnd,hdc); return; } void circlePoints(int xCenter, int yCenter, int x, int y){ setPixel(xCenter + x, yCenter + y); setPixel(xCenter - x, yCenter + y); setPixel(xCenter + x, yCenter - y); setPixel(xCenter - x, yCenter - y); setPixel(xCenter + y, yCenter + x); setPixel(xCenter - y, yCenter + x); setPixel(xCenter + y, yCenter - x); setPixel(xCenter - y, yCenter - x); } void drawCircle(int xCenter, int yCenter, int radius){ int x = 0; int y = radius; int p = 1 - radius; circlePoints(xCenter, yCenter, x, y); while(x Output
Loading...