Created
July 22, 2016 22:30
-
-
Save TimSC/473a8c5743c6e4623ee2297e49ae47dc to your computer and use it in GitHub Desktop.
My solution to the non-rectangular StencilView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
#My solution to the non-rectangular StencilView | |
#Released by Tim Sheerman-Chase under CC0 | |
from kivy.uix.widget import Widget | |
from kivy.graphics import Color, Rectangle, ClearColor | |
from kivy.graphics.vertex_instructions import Triangle, Mesh, Line | |
from kivy.core.image import Image | |
from kivy.graphics.stencil_instructions import StencilPush, StencilPop, StencilUse, StencilUnUse | |
from kivy.graphics.tesselator import Tesselator | |
class StencilMesh(Widget): | |
def __init__(self, **kwargs): | |
super(StencilMesh, self).__init__(**kwargs) | |
self.canvas.after.add(StencilUnUse()) | |
self.canvas.after.add(StencilPop()) | |
self.rectShape = True | |
self.meshes=[] | |
self.bind(pos=self.update_bg) | |
self.bind(size=self.update_bg) | |
self.refresh_instructions() | |
def update_bg(self, *args): | |
if self.rectShape: | |
self.update_rect_shape() | |
def update_rect_shape(self): | |
self.set_mesh_shape([self.pos[0], self.pos[1], | |
self.pos[0]+self.size[0], self.pos[1], | |
self.pos[0]+self.size[0], self.pos[1]+self.size[1], | |
self.pos[0], self.pos[1]+self.size[1]]) | |
def refresh_instructions(self): | |
self.canvas.before.clear() | |
self.canvas.before.add(StencilPush()) | |
for vertices, indices in self.meshes: | |
self.canvas.before.add(Mesh( | |
vertices=vertices, | |
indices=indices, | |
mode="triangle_fan", | |
)) | |
self.canvas.before.add(StencilUse()) | |
def set_mesh_shape(self, shape): | |
tess = Tesselator() | |
tess.add_contour(shape) | |
if not tess.tesselate(): | |
print "Tesselator didn't work :(" | |
self.meshes = [] | |
return | |
self.meshes = tess.meshes | |
self.refresh_instructions() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment