1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pycairoで作成したimageをファイルにしないでkivyのcanvasに描画させたい

Last updated at Posted at 2017-07-18

kivyでcairoを使いたかった。
ファイルを吐き出すのは嫌だった。
ただそれだけ。

自分の環境ではpycairoをインストールできなかったのでcairocffiを利用しています。
環境

  • Ubuntu 16.04
  • python 3.6.1
  • kivy 1.10.0
import cairocffi as cairo
import math
import io

from kivy.config import Config
Config.set('graphics', 'width', '300')
Config.set('graphics', 'height', '200')

from kivy.core.image import Image as CoreImage
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle

class HinomaruApp(App):
    #cairoで日の丸を描画
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 300, 200)
    context = cairo.Context(surface)
    context.set_source_rgb(1,1,1)
    context.rectangle(0,0, 300,200)
    context.fill()
    context.set_source_rgb(1, 0, 0)
    context.arc(150, 100, 66, 0, 2 * math.pi)
    context.fill()
    def build(self):
        widget = Widget()
        bio = io.BytesIO()
        self.surface.write_to_png(bio)
        im = CoreImage.load(io.BytesIO(bio.getvalue()), ext='png')
        texture = im.texture
        with widget.canvas:
            Rectangle(texture=texture, size=(300, 200))
        return widget

if __name__ == '__main__':
    HinomaruApp().run()

Image Widgetを利用したい場合は

- from kivy.graphics import Rectangle
+ from kivy.uix.image import Image


-        with widget.canvas:
-            Rectangle(texture=texture, size=(300, 200))
+        widget.add_widget(Image(texture=texture, size=(300,200)))

で行ける模様

結果

hinomaru.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?