人気ブログランキング | 話題のタグを見る

cairoの文字の位置

文字の中心座標を持つクラスをつくった。
でも、Rangeが使えない。
もう、ひと工夫必要だ。

#!usr/bin/env ruby

require 'sdl'
require 'cairo'

class BackGround
def initialize(w, h)
@w, @h = w, h
end

def update(c)
c.set_source_color(Cairo::Color::WHITE)
c.rectangle(0, 0, @w, @h)
c.fill
end
end

class Moji1
def initialize(w, h)
@x, @y = w / 2, h / 3
@text = 'Cairo on Ruby/SDL'
end

def update(c)
c.matrix = Cairo::Matrix.translate(@x, @y)
c.set_source_color(Cairo::Color::RED)
c.font_size = 50
extents = c.text_extents(@text)
x = extents.width / 2 + extents.x_bearing
y = extents.height / 2 + extents.y_bearing
c.move_to(-x, -y)
c.show_text(@text)
end
end

class Moji2
def initialize(w, h)
@x, @y = w / 2, h / 3 * 2
@text = 'Cairo on Ruby/SDL'
end

def update(c)
c.matrix = Cairo::Matrix.translate(@x, @y)
c.set_source_color(Cairo::Color::ORANGE)
c.font_size = 75
extents = c.text_extents(@text)
x = extents.width / 2 + extents.x_bearing
y = extents.height / 2 + extents.y_bearing
c.move_to(-x, -y)
c.text_path(@text)
c.fill_preserve
c.set_source_color(Cairo::Color::TEAL)
c.stroke
end
end

class Phase
def initialize(screen)
@screen = screen
@w, @h = @screen.w, @screen.h
@image = Cairo::ImageSurface.new(@w, @h)
@bg = BackGround.new(@w, @h)
@moji1 = Moji1.new(@w, @h)
@moji2 = Moji2.new(@w, @h)
end

def update
context = Cairo::Context.new(@image)
@bg.update(context)
@moji1.update(context)
@moji2.update(context)
surface = SDL::Surface.new_from(@image.data, @image.width, @image.height, 32, @image.stride, 0, 0, 0, 0)
@screen.put(surface, 0, 0)
end

def run
loop do
while e=SDL::Event.poll
exit if e.kind_of?(SDL::Event::Quit) || (e.kind_of?(SDL::Event::KeyDown) && e.sym == SDL::Key::ESCAPE)
end
self.update
@screen.flip
SDL.delay(20)
end
end
end

SDL.init(SDL::INIT_VIDEO)
@screen = SDL::Screen.open(500, 350, SDL::Screen.info.bpp, SDL::SWSURFACE)
Phase.new(@screen).run
by gaziya | 2011-05-17 22:19