function DrawLineBresenham(x1,y1,x2,y2)
%sort by x,sure x1<x2.
if x1>x2
tmp=x1;
x1=x2;
x2=tmp;
tmp=y1;
y1=y2;
y2=tmp;
end
dx=x2-x1;
dy=y2-y1;
twoDy=2*dy;
twoDy_Dx=2*(dy-dx);
twoDx=2*dx;
twoDx_Dy=2*(dx-dy);
twoDxPlusDy=2*(dx+dy);
%branch 1: k>0 ?
%k>0 <=> dy>0 if dy>0 %k>0
if dx==0 %if k==INF
for i=y1:y2
plot(x1,i,'*');
hold('on');
end
return ;
end
%branch 2:k=INF %branch 3: k<1 <=> dy<dx
if dy<dx %k<1
p= twoDy-dx;
plot(x1,y1,'*');
hold('on');
while x1<x2
x1=x1+1;
if(p<0)
p=p+twoDy;
else
y1=y1+1;
p=p+twoDy_Dx;
end
plot(x1,y1,'*');
hold('on');
end elseif dy>dx %k>1
p =dy;
plot(x1,y1,'*');
hold('on');
while y1<y2
y1=y1+1;
if p<0
p=p+twoDx;
else
x1=x1+1;
p=p+twoDx_Dy;
end
plot(x1,y1,'*');
hold('on'); end else %k==1 for i=x1:x2
plot(i,y1-x1+i,'*');
hold('on');
end
end elseif dy<0 %k<0
if dx==0 %if k==INF
for i=y2:y1
plot(x1,i,'*');
hold('on');
end
return ;
end
if dx+dy>0 %-1<k<0
p=twoDy+dx;
plot(x1,y1,'*');
hold('on');
while x1<x2
x1=x1+1;
if p<0
y1=y1-1;
p=p+twoDxPlusDy;
else
p=p+twoDy;
end
plot(x1,y1,'*');
hold('on');
end
elseif dx+dy<0 %k>-1
p=twoDx-dy;
plot(x1,y1,'*');
hold('on');
while y1>y2
y1=y1-1;
if p<0
x=x+1;
p=p-twoDxPlusDy;
else
p=p-twoDx; end
plot(x1,y1,'*');
hold('on');
end else %k==-1
for i=x1:x2
plot(i,y1+x1-i,'*');
hold('on');
end end else %k==0 for i=x1:x2
plot(i,y1,'*');
hold('on');
end end % y2=flag*y2;
% y1=flag*y1;
% dx=(x2-x1);
% dy=(y2-y1);
% d=[];
% d(1)=2*dy-dx;
% DoubleDy=2*dy;
% DoubleDy_x=2*(dy-dx);
% x=[];
% y=[];
% x(1)=x1;
% y(1)=y1;
% for i=2:10
% x(i)=x(i-1)+1;
% if d(i-1)<0
% d(i)=d(i-1)+DoubleDy;
% y(i)=y(i-1);
% else
% d(i)=d(i-1)+DoubleDy_x;
% y(i)=y(i-1)+1;
% end
% end
% grid on
% plot(x,y,'*');
% grid on
% hold on
% k1=(y2-y1)/(x2-x1);
% b=y2-k1*x2;
% x_a=x1:0.1:x2;
% y_a=k1*x_a+b;
% plot(x_a,y_a);
% title('Bresenham画直线算法');
end