使用Kivy实施VRAM

时间:2018-10-21 22:21:16

标签: kivy kivy-language

我是Kiwy的新手。 我的任务是实现处理器视频内存。 假设我们有一个由10个布尔元素组成的数组。

如果位置i的元素为True,则坐标为[i,0]的像素为绿色,否则为红色。 如何使用kivy来实现这一点,以便在数组元素发生变化时,像素颜色立即发生变化?

1 个答案:

答案 0 :(得分:0)

您可以使用FrameBuffer来实现。在下面的代码中,我没有实现布尔数组,但这很简单。该代码显示了如何处理显示部分:

from kivy.app import App
from kivy.graphics import Fbo, Rectangle
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from array import array

class FboTest(Widget):
    def __init__(self, **kwargs):
        super(FboTest, self).__init__(**kwargs)
        self.fbo_size = 256

        # first step is to create the fbo and use the fbo texture on a Rectangle
        with self.canvas:
            # create the fbo
            self.fbo = Fbo(size=(self.fbo_size, self.fbo_size))

            # show our fbo on the widget in a Rectangle
            Rectangle(size=(self.fbo_size, self.fbo_size), texture=self.fbo.texture)

        size = self.fbo_size * self.fbo_size
        buf = [255, 0, 0] * size  # initialize buffer to all red pixels
        # initialize the array with the buffer values
        self.arr = array('B', buf)
        # now blit the array
        self.fbo.texture.blit_buffer(self.arr, colorfmt='rgb', bufferfmt='ubyte')


class FboPlayApp(App):

    def build(self):
        root = FloatLayout(size_hint=(None, None), size=(750, 750))
        self.fbotest = FboTest(size_hint=(None, None), size=(512, 512))
        button = Button(text='click', size_hint=(None, None), size=(75, 25), pos=(500, 500), on_release=self.do_button)
        root.add_widget(self.fbotest)
        root.add_widget(button)
        return root

    def do_button(self, *args):
        # set some pixels to green
        for x in range(64, 84):
            for y in range(25, 45):
                self.set_pixel(x, y, True)
        # blit the updated pixels to the FBO
        self.fbotest.fbo.texture.blit_buffer(self.fbotest.arr, colorfmt='rgb', bufferfmt='ubyte')

    def set_pixel(self, x, y, isGreen):
        # set pixel at (x,y) to green if isGreen is True, otherwise turn them red
        index = y * self.fbotest.fbo_size * 3 + x * 3
        if isGreen:
            self.fbotest.arr[index] = 0
            self.fbotest.arr[index+1] = 255
            self.fbotest.arr[index+2] = 0
        else:
            self.fbotest.arr[index] = 255
            self.fbotest.arr[index+1] = 0
            self.fbotest.arr[index+2] = 0

if __name__ == "__main__":
    FboPlayApp().run()

运行此应用程序,然后单击按钮将某些像素的颜色从红色更改为绿色。