shape.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Created: 2019-01-04
  2. # Copyright (c) 2019 Manfred Moitzi
  3. # License: MIT License
  4. from typing import Union, Iterable, List, TYPE_CHECKING
  5. import math
  6. from .vector import Vec2
  7. from .construct2d import ConstructionTool
  8. from .bbox import BoundingBox2d
  9. if TYPE_CHECKING:
  10. from ezdxf.eztypes import Vertex
  11. class Shape2d(ConstructionTool):
  12. """
  13. 2d geometry object as vertices list which can be moved, rotated and scaled.
  14. """
  15. def __init__(self, vertices: Iterable['Vertex'] = None):
  16. self.vertices = [] if vertices is None else Vec2.list(vertices) # type: List[Vec2]
  17. def move(self, dx: float, dy: float) -> None:
  18. self.translate(Vec2((dx, dy)))
  19. def bounding_box(self)->BoundingBox2d:
  20. return BoundingBox2d(self.vertices)
  21. def translate(self, vector: 'Vertex') -> None:
  22. delta = Vec2(vector)
  23. self.vertices = [v + delta for v in self.vertices]
  24. def scale(self, sx: float = 1., sy: float = 1.) -> None:
  25. self.vertices = [Vec2((v.x * sx, v.y * sy)) for v in self.vertices]
  26. def scale_uniform(self, scale: float) -> None:
  27. self.vertices = [v * scale for v in self.vertices]
  28. def rotate(self, angle: float, center: 'Vertex' = None) -> None:
  29. self.rotate_rad(math.radians(angle), center)
  30. def rotate_rad(self, angle: float, center: 'Vertex' = None) -> None:
  31. if center is not None:
  32. center = Vec2(center)
  33. self.translate(-center) # faster than a Matrix44 multiplication
  34. self.vertices = [v.rotate(angle) for v in self.vertices]
  35. if center is not None:
  36. self.translate(center) # faster than a Matrix44 multiplication
  37. # Sequence interface
  38. def __len__(self) -> int:
  39. return len(self.vertices)
  40. def __getitem__(self, item: Union[int, slice]) -> Vec2:
  41. return self.vertices[item]
  42. # limited List interface
  43. def append(self, vertex: 'Vertex') -> None:
  44. self.vertices.append(Vec2(vertex))
  45. def extend(self, vertices: Iterable) -> None:
  46. self.vertices.extend(Vec2.generate(vertices))