Looking at the docs it appears that all of the drawing instructions can take a texture, so I created a small experiment.
I copied the core of the KivyGradient code ( it is just 2 methods) and drew a random line with a texture. One strange effect, the texture needed to be updated or the line turns white. I bound to the Window draw... This feels hacky. It might be worth copying
the gradient to a file, and trying the source attribute.
Anyway - here is the code.
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.graphics.texture import Texture
from kivy.properties import ObjectProperty
from kivy.utils import colormap, get_random_color
from kivy.clock import Clock
from kivy.core.window import Window
from itertools import chain
kv = """
<GradientWidget>:
canvas:
Line:
width: 2
points: [100, 100, 600, 100, 100, 200, 300, 500] # just some random points
texture: self.gradient
BoxLayout:
GradientWidget:
id: gw
"""
class Gradient:
"""
"""
@staticmethod
def horizontal(*args):
"""
Create a horizontal gradient
:param args: colors that will make up the gradient in order
:return: A Texture of the desired gradient
"""
texture = Texture.create(size=(len(args), 1), colorfmt='rgba')
buf = bytes([int(v * 255) for v in chain(*args)]) # flattens
texture.blit_buffer(buf, colorfmt='rgba', bufferfmt='ubyte')
return texture
@staticmethod
def vertical(*args):
"""
Create a Vertical gradient
:param args: colors that will make up the gradient in order
:return: A Texture of the desired gradient
"""
texture = Texture.create(size=(1, len(args)), colorfmt='rgba')
buf = bytes([int(v * 255) for v in chain(*args)]) # flattens
texture.blit_buffer(buf, colorfmt='rgba', bufferfmt='ubyte')
return texture
class GradientWidget(Widget):
gradient = ObjectProperty()
def set_gradient(self, *args):
try:
colors = [colormap[arg] for arg in args]
self.gradient = Gradient.horizontal(*colors)
except KeyError:
print('KeyError: invalid color used')
class GradientExperiment(App):
def build(self):
Window.bind(on_draw=self.win_update) # need to update texture on redraw?
return Builder.load_string(kv)
def set_colors(self):
self.root.ids.gw.set_gradient('red', 'yellow', 'green', 'lightgreen', 'lightblue',
'darkblue', 'violet')
def set_random_colors(self, dt):
self.root.ids.gw.gradient = Gradient.horizontal(*[get_random_color() for _ in range(5)])
def win_update(self, *args):
self.set_colors()
GradientExperiment().run()