計算機圖形學學習(二) Bresenham畫圓算法講解及matlab實現

Bresenham畫圓算法介紹

  • 先講解1/8圓:設圓的半徑爲r,考慮圓心在(0,0),從x=0、y=r開始的順時針方向的1/8圓周的生成過程。

  • x每次增加1個單位,從x=0開始,到x=y結束,即有xi+1=xi+1;另外,yi+1則在yi或者yi-1中選擇(如圖)
    在這裏插入圖片描述

  • yi+1的取值取決於d1和d2的大小
    y2= r2-(xi+1)2
    d1= yi2-y2= yi2-r2+(xi+ 1)2
    d2 = y2-(yi-1)2 = r2-(xi+1)2- (yi一1)2
    令pi=d1- d2,代人d1、d2
    pi = 2(xi+1)2+yi2+(yi- 1)2 - 2r2

  • pi稱爲誤差項。如果pi<0,則下一個像素點yi+1=yi,
    否則yi+1=yi-1(其中pi=0時選擇yi+1=yi-1)

  • pi的遞歸式爲:
    pi+1 = pi+4xi+6+2(yi2 +1-yi2)- 2(yi+1-yi)
    pi的初值代xi=0,yi=r可得:
    p0= 2(0+1)2+r2 +(r- 1)22 = 3一2r


Bresenham畫圓算法實現

根據上面的推導,圓生成算法思路如下:
(1)求誤差初值,p0=3- 2r,i=1,畫點(0,r)
(2)求下一個點的y座標,其中xi+1=xi+1,如果pi<0則yi+1=yi,否則yi+1=yi-1
(3)畫點(xi+1,yi+1)
(4)計算下一個誤差,如果pi<0則pi+1=pi+4xi+6,否則pi+1=pi+4(xi-yi)+10
(5) i=i+1,如果x=y則結束,否則返回步驟(2)。


matlab代碼實現

function Bresenhamcircle(xc,yc,r,color)
x=0;
y=r;
p=3-2*r;
hold on
grid minor
while(x<y)
    scatter(xc+x,yc+y,'.',color)
    scatter(xc-x,yc+y,'.',color)
    scatter(xc+x,yc-y,'.',color)
    scatter(xc-x,yc-y,'.',color)
    scatter(xc+y,yc+x,'.',color)
    scatter(xc-y,yc+x,'.',color)
    scatter(xc+y,yc-x,'.',color)
    scatter(xc-y,yc-x,'.',color)
    if(p<0)
        p=p+4*x+6;
    else
        p=p+4*(x-y)+10;
        y=y-1;
    end
    x=x+1;
end
if(x==y)
    scatter(xc+x,yc+y,'.',color)
    scatter(xc-x,yc+y,'.',color)
    scatter(xc+x,yc-y,'.',color)
    scatter(xc-x,yc-y,'.',color)
    scatter(xc+y,yc+x,'.',color)
end
hold off
end

結果展示

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章