Download code

Jump to: navigation, search

Back to Bresenham's_line_algorithm_(Python)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

bresenham_line.py

 1 # The authors of this work have released all rights to it and placed it
 2 # in the public domain under the Creative Commons CC0 1.0 waiver
 3 # (http://creativecommons.org/publicdomain/zero/1.0/).
 4 # 
 5 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 # 
13 # Retrieved from: http://en.literateprograms.org/Bresenham's_line_algorithm_(Python)?oldid=19587
14 
15 from Tkinter import *
16 
17 class BresenhamCanvas(Canvas):
18     def draw_point(self, x, y, color="red"):
19         self.create_line(x, y, x, y, fill=color)
20 
21     def draw_line(self, x0, y0, x1, y1, color="red"):
22         steep = abs(y1 - y0) > abs(x1 - x0)
23         if steep:
24             x0, y0 = y0, x0  
25             x1, y1 = y1, x1
26 
27         if x0 > x1:
28             x0, x1 = x1, x0
29             y0, y1 = y1, y0
30         
31     
32             
33         deltax = x1 - x0
34         deltay = abs(y1 - y0)
35         error = 0
36         y = y0
37             
38         for x in range(x0, x1):
39 	    if steep:
40 	        self.draw_point(y, x, color)
41 	    else:
42 	        self.draw_point(x, y, color)
43 	            
44 
45 	    if (error << 1) >= deltax:
46 	        y = y + 1
47 	        error = error + 2*(deltay - deltax)
48 	    else:
49 	        error = error + 2*deltay
50 
51                 
52 if __name__ == "__main__":
53 
54     import math
55     CANVAS_SIZE = 400
56 
57     root = Tk()
58     canvas = BresenhamCanvas(root, width=CANVAS_SIZE, height=CANVAS_SIZE)
59     canvas.pack()
60     
61     margin = CANVAS_SIZE / 10
62     
63     xcenter = int(CANVAS_SIZE / 2)
64     ycenter = int(CANVAS_SIZE / 2)
65     line_length = ((CANVAS_SIZE / 2) - margin)
66     
67     n_lines = 200
68     angle_step = (2 * math.pi) / n_lines
69     
70     for i in range(n_lines):
71         theta = angle_step * i
72         xstart = int(margin * math.cos(theta)) + xcenter
73         ystart = int(margin * math.sin(theta)) + ycenter
74         xend = int(line_length * math.cos(theta)) + xcenter
75         yend = int(line_length * math.sin(theta)) + ycenter
76         canvas.draw_line(xstart, ystart, xend, yend, color="blue")
77         
78     root.mainloop()
79 


hijacker
hijacker
hijacker
hijacker