Bresenham算法画五角星

2019-09-23  本文已影响0人  周末的游戏之旅
{
    float x[5], y[5];   //五角星坐标
    int R = 100;        //半径
    float ox = 100,oy=100; //圆心
    float Pi = 3.1415926536f;
    CPaintDC dc(this); // device context for painting
                       // TODO: 在此处添加消息处理程序代码
                       // 不为绘图消息调用 CView::OnPaint()
//坐标初始化
    for (int i = 0; i <= 4; i++)         
    {
        x[i] = R * cos(2 * Pi*i / 5)+ox;
        y[i] = R * sin(2 * Pi*i / 5)+oy;
    }

    //连线
    BresenhamLine(x[0], x[2], y[0], y[2], RGB(0, 255, 255));
    BresenhamLine(x[2], x[4], y[2], y[4], RGB(0, 255, 255));
    BresenhamLine(x[4], x[1], y[4], y[1], RGB(0, 255, 255));
    BresenhamLine(x[1], x[3], y[1], y[3], RGB(0, 255, 255));
    BresenhamLine(x[3], x[0], y[3], y[0], RGB(0, 255, 255));
}


void CBresenhamStarView::BresenhamLine(int x1, int x2, int y1, int y2, int color)
{
    CClientDC dc(this);
    dc.SetPixel(x1, y1, color); //画出起点
    int dx = abs(x2 - x1);
    int dy = abs(y2 - y1);

    if (dx == 0 && dy == 0) {   //此时起点与终点相同,结束
        return;
    }

    int flag = 0;

    if (dx < dy) {       //斜率小于0交换x,y值
        flag = 1;
        swap(&x1, &y1);
        swap(&x2, &y2);
        swap(&dx, &dy);
    }

    int tx = (x2 - x1) > 0 ? 1 : -1;
    int ty = (y2 - y1) > 0 ? 1 : -1;
    int curx = x1;
    int cury = y1;
    int dS = 2 * dy;
    int dT = 2 * (dy - dx);
    int d = dS - dx;    //起点判别式 2△y-△x=dS-dx
    while (curx != x2)
    {
        if (d < 0)
            d += dS;
        else {
            cury += ty;
            d += dT;
        }
        if (flag) {
            dc.SetPixel(cury, curx, color);
        }
        else {
            dc.SetPixel(curx, cury, color);
        }
        curx += tx;
    }

}


void CBresenhamStarView::swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;

}
上一篇下一篇

猜你喜欢

热点阅读