|
| 1 | +import pygame |
| 2 | +from pygame.locals import * |
| 3 | + |
| 4 | +from py2d.Bezier import * |
| 5 | +from py2d.Math import * |
| 6 | +import py2d.examples.Main |
| 7 | + |
| 8 | +SELECTION_DISTANCE = 20 |
| 9 | + |
| 10 | +class Bezier(py2d.examples.Main.Example): |
| 11 | + """Bezier curve sample |
| 12 | + |
| 13 | + Draw around end and control points of the bezier curve. |
| 14 | +
|
| 15 | + Key mappings: |
| 16 | + MOUSE1: Drag points |
| 17 | +
|
| 18 | + Have fun! |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self, runner): |
| 22 | + self.runner = runner |
| 23 | + self.title = "Simple Drawing" |
| 24 | + |
| 25 | + self.p1 = Vector(200,400) |
| 26 | + self.p2 = Vector(400,400) |
| 27 | + self.c1 = Vector(500,50) |
| 28 | + self.c2 = Vector(100,50) |
| 29 | + |
| 30 | + |
| 31 | + self.points = ( ('P1', (255,0,0), self.p1), |
| 32 | + ('P2', (255,0,0), self.p2), |
| 33 | + ('C1', (0,255,0), self.c1), |
| 34 | + ('C2', (0,255,0), self.c2) ) |
| 35 | + |
| 36 | + self.sel_point = None |
| 37 | + |
| 38 | + def update(self, time_elapsed): |
| 39 | + pass |
| 40 | + |
| 41 | + def render(self): |
| 42 | + |
| 43 | + pygame.draw.line(self.runner.screen, 0x006600, self.p1.as_tuple(), self.c1.as_tuple()) |
| 44 | + pygame.draw.line(self.runner.screen, 0x006600, self.p2.as_tuple(), self.c2.as_tuple()) |
| 45 | + |
| 46 | + for label, color, pos in self.points: |
| 47 | + self.draw_point(pos, color, label) |
| 48 | + |
| 49 | + bezier = [self.p1] + flatten_cubic_bezier(self.p1, self.p2, self.c1, self.c2) + [self.p2] |
| 50 | + |
| 51 | + pygame.draw.lines(self.runner.screen, 0xffffff, False, [p.as_tuple() for p in bezier], 2) |
| 52 | + |
| 53 | + if self.sel_point: |
| 54 | + pygame.draw.ellipse(self.runner.screen, 0xfff00, pygame.Rect( (self.sel_point.x - 4, self.sel_point.y - 4), (8,8)) , 1) |
| 55 | + |
| 56 | + def draw_point(self, p, color, label=None): |
| 57 | + pygame.draw.ellipse(self.runner.screen, color, pygame.Rect(p.as_tuple(), (2,2))) |
| 58 | + if label: |
| 59 | + self.runner.screen.blit(self.runner.font.render(label, False, color), p.as_tuple()) |
| 60 | + |
| 61 | + def mouse_down(self, pos, button): |
| 62 | + if button == 1: |
| 63 | + mouse = Vector(*pos) |
| 64 | + |
| 65 | + nearest = min(self.points, key=lambda p: (p[2]-mouse).length) |
| 66 | + |
| 67 | + if (nearest[2] - mouse).length_squared <= SELECTION_DISTANCE: |
| 68 | + self.sel_point = nearest[2] |
| 69 | + else: |
| 70 | + self.sel_point = None |
| 71 | + |
| 72 | + def mouse_move(self, pos, rel, buttons): |
| 73 | + if buttons[0] and self.sel_point: |
| 74 | + self.sel_point.x, self.sel_point.y = pos |
0 commit comments