-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBresenhams.py
62 lines (53 loc) · 1.85 KB
/
Bresenhams.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from typing import Tuple, List
from LineDrawing.LineDrawingStrategy import LineDrawingStrategy
class BresenhamLineDrawing(LineDrawingStrategy):
@staticmethod
def draw(startPoint: Tuple[int, int], endPoint: Tuple[int, int]) -> List[Tuple[int, int]]:
x1, y1 = startPoint
x2, y2 = endPoint
rise: int = (y2 - y1)
run: int = (x2 - x1)
slopeIsNegative: bool = (rise < 0) ^ (run < 0)
points: List[Tuple[int, int]] = []
rise: int = abs(rise)
run: int = abs(run)
if (run > rise):
# x increases faster than y
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
points.append((x1, y1))
y = y1
pk: int = 2 * rise - run # magic formula
for x in range(x1 + 1, x2 + 1):
if pk < 0:
# Select yk since dl < du
points.append((x, y))
pk += 2 * rise
else:
if slopeIsNegative:
y -= 1
else:
y += 1
points.append((x, y))
pk += (2 * rise) - (2 * run)
else:
# y increases faster than x
if y1 > y2:
y1, y2 = y2, y1
x1, x2 = x2, x1
points.append((x1, y1))
x = x1
pk: int = 2 * run - rise # magic formula
for y in range(y1 + 1, y2 + 1):
if pk < 0:
points.append((x, y))
pk += 2 * run
else:
if slopeIsNegative:
x -= 1
else:
x += 1
points.append((x, y))
pk += (2 * run) - (2 * rise)
return points