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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| from decimal import * import math import time
class Line(object): def __init__(self, start=(0, 0), enda=0, endd=0, angle=0, length=0): """ start 起点,默认(0,0) enda 终点绝对值 (x,y) endd 终点增量值 (x,y) angle 直线角度 (-180,180] length 直线长度 """ self.start = tuple( map(lambda x: Decimal(str(x)).quantize(Decimal("0.000")), start))
self.zoom = Decimal(1000) self.delta = Decimal(1) / self.zoom
if enda: self.end = tuple( map(lambda n: Decimal(str(n)).quantize(Decimal("0.000")), enda)) elif endd: self.end = tuple( map(lambda n: Decimal(str(n)).quantize(Decimal("0.000")), endd)) elif angle and length: angle = Decimal(str(math.radians(angle))) length = Decimal(str(length)) self.end = ( start[0] + Decimal(str(math.cos(angle))) * length, start[1] + Decimal(str(math.sin(angle))) * length,) self.end = tuple( map(lambda n: Decimal(str(n)).quantize(Decimal("0.000")), self.end)) else: self.end = (Decimal("0"), Decimal("0"))
def __str__(self) -> str: return "start=({:,.3f},{:,.3f}); end=({:,.3f},{:,.3f})".format( float(self.start[0]), float(self.start[1]), float(self.end[0]), float(self.end[1]),)
def __offset(self) -> None: xe = self.end[0] - self.start[0] ye = self.end[1] - self.start[1] self.end = (xe, ye) self.f = 0 self.step = abs(xe) + abs(ye) self.step = self.step * self.zoom self.kx = int(math.copysign(1, xe)) self.ky = int(math.copysign(1, ye))
def __compensation(self) -> None: if self.f >= 0: if self.end[0] == 0: self.y = self.y + self.delta * self.ky self.f = self.f else: self.x = self.x + self.delta * self.kx self.f = self.f - abs(self.end[1]) else: self.y = self.y + self.delta * self.ky self.f = self.f + abs(self.end[0])
def __iter__(self): self.__offset() self.x = Decimal(0) self.y = Decimal(0) return self
def __next__(self): if self.step: self.__compensation() self.step = self.step - 1 return (float(self.x + self.start[0]), float(self.y + self.start[1])) else: raise StopIteration
|