使用kivy textu创建频谱

2024-04-26 05:48:02 发布

您现在位置:Python中文网/ 问答频道 /正文

根据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))

Something like this


Tags: to代码from文档posselfsizecreate
3条回答

您可以为此创建一个嵌套循环。
如果您循环像素,并设置颜色。
最简单的方法是使用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()

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()

诀窍是尝试显示比其大小更大的纹理。 result

相关问题 更多 >