根据Kivy文档,这段代码可用于创建黑白渐变。如何使用kivy纹理创建光谱? 我一直在尝试操作样本变量,但我得到的只是两种颜色之间的渐变。
texture = Texture.create(size=(64, 64))
# create 64x64 rgb tab, and fill with values from 0 to 255
# we'll have a gradient from black to white
size = 64 * 64 * 3
buf = [int(x * 255 / size) for x in range(size)]
buf = b''.join(map(chr, buf))
texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')
with self.canvas:
Rectangle(texture=texture, pos=self.pos, size=(64, 64))
答案 0 :(得分:1)
你可以为它做一个嵌套循环 如果循环通过像素,并设置颜色 最简单的方法是使用hsv,然后转换为rgb 因此外部循环设置v(值),因为这将是每行的变化 内环将是h(色调),行中的每个像素 你可以做这样的事情。
from kivy.app import App
from kivy.graphics.texture import Texture
from kivy.graphics import Rectangle
from kivy.uix.boxlayout import BoxLayout
from colorsys import hsv_to_rgb
class MyLayout(BoxLayout):
def __init__(self,**kwargs):
super(MyLayout,self).__init__(**kwargs)
w = 64
h = 64
texture = Texture.create(size=(w, h))
buf = []
for i in range(h):
for j in range(w):
color = hsv_to_rgb(j/float(w),1,i/float(h)) # colorsys takes (0,0,0) to (1,1,1)
pixel = [int(a*b) for a,b in zip(color,[255,255,255])] # since color goes from (0,0,0) to (1,1,1), we multiply by 255
buf.extend(pixel)
buf = b''.join(map(chr, buf))
texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')
with self.canvas:
Rectangle(texture=texture, pos=self.pos, size=(w, h))
class MyApp(App):
def build(self):
return MyLayout()
if __name__ == "__main__":
MyApp().run()
答案 1 :(得分:0)
从this得到一些灵感,我最终得到了这段代码和结果。
from itertools import chain
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle
from kivy.graphics.texture import Texture
class MyWidget(Widget):
def __init__(self, **args):
super(MyWidget, self).__init__(**args)
self.texture = Texture.create(size=(5, 1), colorfmt="rgb")
pixels = bytes([int(v * 255) for v in chain((0, 0, 0, 1), (0, 0, 0, 1))])
buf = ''.join(pixels)
self.texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')
with self.canvas:
Rectangle(pos=self.pos, size=self.size, texture=self.texture)
class TestApp(App):
def build(self):
return MyWidget(size=(368, 512))
if __name__ == '__main__':
TestApp().run()