Ruby-Cairo の練習

フォントのインストール

まずは、任意の TTF フォントでテキストを描画したいので、インストールからはじめました。

$ mkdir ~/.fonts
$ cp *ttf ~/.fonts/
$ fc-cache

サンプル

とりあえず、Rubyist Magazine - cairo: 2 次元画像描画ライブラリVikiWiki - rcairo を参考にサンプルを作りました。

プリミティブの描画とテキストの描画、そして png への出力を試しています。

require 'rubygems'
require 'cairo'

format = Cairo::FORMAT_ARGB32
width = 300
height = 200
radius = height / 3 # 半径

surface = Cairo::ImageSurface.new(format, width, height)
context = Cairo::Context.new(surface)

# 背景
context.set_source_rgb(1, 1, 1) # 白
context.rectangle(0, 0, width, height)
context.fill

# 赤丸
context.set_source_rgb(1, 0, 0) # 赤
context.arc(width / 2, height / 2, radius, 0, 2 * Math::PI)
context.fill

# text string
context.set_source_rgb(0, 0, 0)
context.select_font_face("XXXXX")  # XXX にフォントファイル名を入れる(.ttf は抜く)
context.set_font_size( 24 )
context.move_to(0,100)
str = "文字コードの自動判別 -- Text String"
context.show_text( str )

surface.write_to_png("hinomaru.png")

結果

こんな png ファイルが出力されました。
横幅が足りなくて、テキストが途中で切れてしまっています。

hinomaru