Stencil instructions

New in version 1.0.4.

Changed in version 1.3.0.

Stencil instructions permit you to draw and use the current drawing as a mask. Even if you don’t have as much control as OpenGL, you can still do fancy things :=)

The stencil buffer can be controled with theses 3 instructions :

  • StencilPush: push a new stencil layer any drawing that happening here will be used as a mask
  • StencilUse : now draw the next instructions and use the stencil for masking them
  • StencilUnUse : stop drawing, and use the stencil to remove the mask
  • StencilPop : pop the current stencil layer.

Here is a global scheme to respect:

.. code-block:: kv

StencilPush

# PHASE 1: put here any drawing instruction to use as a mask

StencilUse

# PHASE 2: all the drawing here will be automatically clipped by the previous mask

StencilUnUse

# PHASE 3: put here the same drawing instruction as you did in PHASE 1

StencilPop

Limitations

  • Drawing in PHASE 1 and PHASE 3 must not collide between each others, or you will get unexpected result.
  • The stencil is activated as soon as you’re doing a StencilPush
  • The stencil is deactivated as soon as you’ve correctly pop all the stencils layers
  • You must not play with stencil yourself between a StencilPush / StencilPop
  • You can push again the stencil after a StencilUse / before the StencilPop
  • You can push up to 128 layers of stencils. (8 for kivy < 1.3.0)

Example of stencil usage

Here is an example, in kv style:

StencilPush

# create a rectangle mask, from pos 100, 100, with a 100, 100 size.
Rectangle:
    pos: 100, 100
    size: 100, 100

StencilUse

# we want to show a big green rectangle, however, the previous stencil
# mask will crop us :)
Color:
    rgb: 0, 1, 0
Rectangle:
    size: 900, 900

StencilUnUse:
    # new in kivy 1.3.0, remove the mask previoulsy added
    Rectangle:
        pos: 100, 100
        size: 100, 100

StencilPop
class kivy.graphics.stencil_instructions.StencilPush

Bases: kivy.graphics.instructions.Instruction

Push the stencil stack. See module documentation for more information.

class kivy.graphics.stencil_instructions.StencilPop

Bases: kivy.graphics.instructions.Instruction

Pop the stencil stack. See module documentation for more information.

class kivy.graphics.stencil_instructions.StencilUse

Bases: kivy.graphics.instructions.Instruction

Use current stencil buffer as a mask. Check module documentation for more information.

class kivy.graphics.stencil_instructions.StencilUnUse

Bases: kivy.graphics.instructions.Instruction

Use current stencil buffer to unset the mask.