在此记录Bresenham 中点画圆算法,下面直接给出步骤与算法,步骤从计算机图形学一书中截取的,此算法原理在此不做说明,可自行查看计算机图形学一书相关描述。
一、步骤描述
二、代码实现,以OC为开发语言
//以点为类的头文件
@interface ScreenPT : NSObject{
GLint x,y;
}
@property (nonatomic,assign) GLint x;
@property (nonatomic,assign) GLint y;
-(void) setCoordX:(GLint)x Y:(GLint)y;
-(void) incrementX;
-(void) decrementY;
@end
//类的实现文件
#import "ScreenPT.h"
@implementation ScreenPT
@synthesize x;
@synthesize y;
-(id) init{
if (self = [super init]) {
x = 0;
y = 0;
}
return self;
}
-(void) setCoordX:(GLint)x Y:(GLint)y{
self.x = x;
self.y = y;
}
-(void) incrementX{
self.x++;
}
-(void) decrementY{
self.y--;
}
@end
//实现文件及相关辅助方法
void setPixel(GLint x,GLint y){
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
//MARK: Bresenham 中点画圆算法
void circleMidpoint(){
GLint xc = 100,yc = 100,radius = 30;//圆心与半径
ScreenPT* spt = [[ScreenPT alloc] init];
GLint p = 1 - radius;
[spt setCoordX:0 Y:radius];
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.5, 1.0, 0.0);
void circlePlotPoints(GLint,GLint,ScreenPT*);
circlePlotPoints(xc, yc, spt);
while (spt.x < spt.y) {
[spt incrementX];
if (p < 0) {
p += 2 * spt.x + 1;
} else {
[spt decrementY];
p += 2 * (spt.x - spt.y) + 1;
}
circlePlotPoints(xc, yc, spt);
}
glFlush();
}
void circlePlotPoints(GLint xc,GLint yc,ScreenPT* spt){
setPixel(xc + spt.x, yc + spt.y);
setPixel(xc - spt.x, yc + spt.y);
setPixel(xc + spt.x, yc - spt.y);
setPixel(xc - spt.x, yc - spt.y);
setPixel(xc + spt.y, yc + spt.x);
setPixel(xc - spt.y, yc + spt.x);
setPixel(xc + spt.y, yc - spt.x);
setPixel(xc - spt.y, yc - spt.x);
}
三、效果图