将该矩形设置为MyPaintWidget的大小,该大小以默认大小在父窗口小部件上绘制.如果MyPaintWidget是根窗口小部件,则设置self.size将允许它占据整个窗口空间. (请注意,尽管当前结构只会在on_touch_down事件上调整画布的大小.因此,如果您调整窗口的大小,则需要单击以调整图像的大小.)
#Change MyPaintApp to the following...
class MyPaintApp(App):
def build(self):
return MyPaintWidget()
您还可以创建一个单独的小部件来保留背景.在下面,我添加了一个MyBackground小部件,该小部件用于背景,并且当屏幕尺寸更改时,该小部件势必会调整大小.也有其他几种方法可以做到这一点.
from random import random
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.graphics import Color, Line, Rectangle
from kivy.uix.filechooser import FileChooserListView, FileChooserIconView
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
class MyBackground(Widget):
def __init__(self, **kwargs):
super(MyBackground, self).__init__(**kwargs)
with self.canvas:
self.bg = Rectangle(source='water.png', pos=self.pos, size=self.size)
self.bind(pos=self.update_bg)
self.bind(size=self.update_bg)
def update_bg(self, *args):
self.bg.pos = self.pos
self.bg.size = self.size
class MyPaintWidget(Widget):
def on_touch_down(self, touch):
color = (random(), random(), random())
with self.canvas:
Color(*color)
d = 30.
touch.ud['line'] = Line(points=(touch.x, touch.y))
def on_touch_move(self, touch):
touch.ud['line'].points += [touch.x, touch.y]
class MyPaintApp(App):
def build(self):
parent = MyBackground()
painter = MyPaintWidget()
parent.add_widget(painter)
return parent
if __name__ == '__main__':
MyPaintApp().run()