#!python -3 # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2019/11/02 08:34:51 +0900> """ Draw and save png file for Kivy. Windows10 x64 1903 + Python 2.7.17 32bit + Kivy 1.11.1 """ from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.image import Image from kivy.graphics import Ellipse from kivy.graphics import Line from kivy.graphics import Rectangle from kivy.graphics import Color from kivy.graphics import Translate from kivy.graphics.texture import Texture from kivy.properties import ObjectProperty from kivy.lang import Builder from kivy.config import Config Config.set('graphics', 'width', '512') Config.set('graphics', 'height', '512') output_filename = "./output.png" # my.kv Builder.load_string(''' #:kivy 1.11.1 : BoxLayout: size: root.size orientation: "vertical" MyPaintImage: id: myimage texture: self.texture_image size_hint_y: 0.9 canvas.before: Color: rgba: 0, 0, 0, 1 Rectangle: pos: self.pos size: self.size BoxLayout: size_hint_y: 0.1 Button: id: btn_draw text: "Draw" on_press: myimage.draw_shapes() Button: id: btn_save text: "Save" on_press: myimage.save_canvas_image() ''') class MyPaintImage(Image): texture_image = ObjectProperty(None) def __init__(self, **kwargs): super(MyPaintImage, self).__init__(**kwargs) self.texture_image = Texture.create(size=self.size) def draw_shapes(self): bx, by = self.pos with self.canvas: Translate(bx, by) Color(0.1, 0.4, 0.1) Rectangle(pos=(0, 0), size=self.size) Color(0, 0.75, 0) Rectangle(pos=(16, 64), size=(300, 200)) poslist = [ 32, 32, 480, 420, 480, 32, ] Color(1, 0, 0, .3) Line(points=poslist, width=6, close='True') Color(0, .5, 1, 0.5) Ellipse(pos=(76, 50), size=(360, 360)) Translate(-bx, -by) def save_canvas_image(self): self.export_to_png(filename=output_filename, scale=1.0) print("save %s" % output_filename) class MyWidget(Widget): def __init__(self, **kwargs): super(MyWidget, self).__init__(**kwargs) class MyApp(App): def __init__(self, **kwargs): super(MyApp, self).__init__(**kwargs) self.title = 'Simple Graphics Test 2' def build(self): return MyWidget() if __name__ == '__main__': MyApp().run()