Skip to content

Instantly share code, notes, and snippets.

@el3
Created September 5, 2024 21:01
Show Gist options
  • Save el3/5eb64b7354b457664c07d337060c2ec0 to your computer and use it in GitHub Desktop.
Save el3/5eb64b7354b457664c07d337060c2ec0 to your computer and use it in GitHub Desktop.
kivy shaderlabel
from kivy.app import App
from kivy.properties import DictProperty
from kivy.uix.effectwidget import AdvancedEffectBase, EffectWidget
from kivy.properties import NumericProperty, ListProperty
from kivy.lang import Builder
from kivy.uix.label import Label
KV = """
BoxLayout:
ShaderLabel:
shader_color: 1.0,0.0,1.0
text: "1"
Label:
ShaderLabel:
shader_color: 1.0,0.0,0.0
text: "2"
"""
class ShaderLabel(Label):
shader_color = ListProperty([0.0,0.0,0.0])
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.shader = Shader()
self.ew = EffectWidget(effects=[self.shader])
self.add_widget(self.ew)
def on_shader_color(self, *args):
self.shader.color = self.shader_color
def on_pos(self, *args):
self.ew.pos = self.pos
self.shader.x, self.shader.y = self.pos
def on_size(self, *args):
self.ew.size = self.size
self.shader.width = self.width
self.shader.height = self.height
class Shader(AdvancedEffectBase):
uniforms = DictProperty(
{'x': 0.0, 'y': 0.0, 'width': 10.0, 'height': 10.0, 'r':0.0, 'g':0.0, 'b':0.0})
x = NumericProperty(0.0)
y = NumericProperty(0.0)
width = NumericProperty(10.0)
height = NumericProperty(10.0)
color = ListProperty([0.0,0.0,0.0])
def on_color(self, _, color):
self.uniforms.r = color[0]
self.uniforms.g = color[1]
self.uniforms.b = color[2]
def on_x(self, _, x):
self.uniforms['x'] = x
def on_y(self, _, y):
self.uniforms['y'] = y
def on_width(self, _, width):
self.uniforms['width'] = float(width)
def on_height(self, _, height):
self.uniforms['height'] = float(height)
glsl = '''
uniform float x;
uniform float y;
uniform float width;
uniform float height;
uniform float r;
uniform float g;
uniform float b;
vec4 effect(vec4 color, sampler2D texture, vec2 tex_coords, vec2 coords) {
if (coords.x > x && coords.x < x+width && coords.y > y && coords.y < x+height) {
return vec4(r, g, b, 1.0);
}
}
'''
class MyApp(App):
def build(self):
return Builder.load_string(KV)
MyApp().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment