kivy - 使用 Kivy 实现 VRAM
问题描述
我是 Kiwy 的新手。我的任务是实现处理器显存。假设我们有一个包含 10 个布尔元素的数组。
如果位置为 i 的元素为 True,则坐标为 [i, 0] 的像素为绿色,否则为红色。如何用 kivy 实现这一点,以便当数组元素发生变化时,像素颜色会立即发生变化?
解决方案
您可以使用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()
运行此应用程序并单击按钮将某些像素的颜色从红色更改为绿色。
推荐阅读
- eclipse - 由于只读属性,在tomcat安装库中分配临时目录导致错误
- azure-ad-b2c - Web 应用程序在调用 Graph API 时挂起
- bash - 如何通过匹配 shell/bash 脚本中的不同文件来替换 for 循环语句
- ag-grid - ag-grid 是否支持列虚拟化?
- spring - Spring jdbc'选择更新'
- database - Postgresql:有没有办法从 PGDATA/base 目录中读取数据并将数据导入新数据库?
- android-studio - 在 pubspec.yaml 中,颤振命令(包升级、包获取、颤振升级、颤振医生)选项不可用我
- oracle - 游标循环内的多个 IF
- c++ - 异常未处理 - 这是 Nullpointer C++
- python - 从另一个函数调用函数时出错