/examples/canvas/stencil_canvas.py

https://github.com/backspac3/kivy · Python · 84 lines · 76 code · 0 blank · 8 comment · 0 complexity · ca1219e1603d02b38da60f6a65f7b5c2 MD5 · raw file

  1. '''
  2. Stencil demo
  3. ============
  4. This is a test of the stencil graphics instruction inside the stencil view
  5. widget. When you use a stencil, every draw outside the bounding box of the
  6. stencil view will be avoid. All the graphics will draw only in the stencil view.
  7. You can "draw" a stencil view by touch & draw. The touch down will set the
  8. position, and the drag will set the size.
  9. '''
  10. from kivy.app import App
  11. from kivy.core.window import Window
  12. from kivy.graphics import Color, Rectangle
  13. from kivy.uix.boxlayout import BoxLayout
  14. from kivy.uix.floatlayout import FloatLayout
  15. from kivy.uix.button import Button
  16. from kivy.uix.label import Label
  17. from kivy.uix.stencilview import StencilView
  18. from random import random as r
  19. from functools import partial
  20. class StencilTestWidget(StencilView):
  21. '''Drag to define stencil area
  22. '''
  23. def on_touch_down(self, touch):
  24. self.pos = touch.pos
  25. self.size = (1, 1)
  26. def on_touch_move(self, touch):
  27. self.size = (touch.x-touch.ox, touch.y-touch.oy)
  28. class StencilCanvasApp(App):
  29. def add_rects(self, label, wid, count, *largs):
  30. label.text = str(int(label.text) + count)
  31. with wid.canvas:
  32. for x in xrange(count):
  33. Color(r(), 1, 1, mode='hsv')
  34. Rectangle(pos=(r() * wid.width + wid.x,
  35. r() * wid.height + wid.y), size=(10, 10))
  36. def reset_stencil(self, wid, *largs):
  37. wid.pos = (0, 0)
  38. wid.size = Window.size
  39. def reset_rects(self, label, wid, *largs):
  40. label.text = '0'
  41. wid.canvas.clear()
  42. def build(self):
  43. wid = StencilTestWidget(size_hint=(None, None), size=Window.size)
  44. label = Label(text='0')
  45. btn_add500 = Button(text='+ 200 rects')
  46. btn_add500.bind(on_press=partial(self.add_rects, label, wid, 200))
  47. btn_reset = Button(text='Reset Rectangles')
  48. btn_reset.bind(on_press=partial(self.reset_rects, label, wid))
  49. btn_stencil = Button(text='Reset Stencil')
  50. btn_stencil.bind(on_press=partial(self.reset_stencil, wid))
  51. layout = BoxLayout(size_hint=(1, None), height=50)
  52. layout.add_widget(btn_add500)
  53. layout.add_widget(btn_reset)
  54. layout.add_widget(btn_stencil)
  55. layout.add_widget(label)
  56. root = BoxLayout(orientation='vertical')
  57. rfl = FloatLayout()
  58. rfl.add_widget(wid)
  59. root.add_widget(rfl)
  60. root.add_widget(layout)
  61. return root
  62. if __name__ == '__main__':
  63. StencilCanvasApp().run()