cairoでお絵かきする必要に迫られた。
IPython notebook上で結果を表示できれば試行錯誤が行い易い。
やり方
以下の関数を最初に定義しておくだけ。
import io
from IPython.display import Image
def surface_to_image(surface):
buf = io.BytesIO()
surface.write_to_png(buf)
data = buf.getvalue()
buf.close()
return Image(data=data)
次のように使える
import cairo
from IPython.display import display
surface=cairo.ImageSurface(cairo.FORMAT_ARGB32, 640, 480)
ctx = cairo.Context(surface)
ctx.set_line_width(1)
ctx.set_source_rgb(0.8,0,0)
ctx.move_to(320, 400)
ctx.curve_to(150, 300, 150, 170, 150, 170)
ctx.curve_to(150, 50, 320, 50, 320, 170)
ctx.curve_to(320, 50, 490, 50, 490, 170)
ctx.curve_to(490, 170, 490, 300, 320, 400)
ctx.fill()
display(surface_to_image(surface))