Class: PNG::Font

Inherits:
Object
  • Object
show all
Defined in:
lib/png/font.rb

Overview

Implements a simple bitmap font by extracting letters from a PNG.

Constant Summary collapse

LETTERS =
(("A".."Z").to_a +
("a".."z").to_a +
("0".."9").to_a + [" "] * 16 +
'({[<!@#$%^&*?_+-=;,"/~>]})'.split(//))

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(png_file) ⇒ Font

Returns a new instance of Font.



20
21
22
23
24
# File 'lib/png/font.rb', line 20

def initialize png_file
  @canvas = PNG.load_file png_file
  @height, @width = canvas.height / 4, canvas.width / 26
  @cache = {}
end

Instance Attribute Details

#canvasObject (readonly)

Returns the value of attribute canvas.



14
15
16
# File 'lib/png/font.rb', line 14

def canvas
  @canvas
end

#heightObject (readonly)

Returns the value of attribute height.



14
15
16
# File 'lib/png/font.rb', line 14

def height
  @height
end

#widthObject (readonly)

Returns the value of attribute width.



14
15
16
# File 'lib/png/font.rb', line 14

def width
  @width
end

Class Method Details

.defaultObject



16
17
18
# File 'lib/png/font.rb', line 16

def self.default
  @@default ||= new(File.join(File.dirname(__FILE__), "default_font.png"))
end

Instance Method Details

#[](c) ⇒ Object



37
38
39
40
41
42
# File 'lib/png/font.rb', line 37

def [] c
  c = c.chr unless String === c
  x0, y0, x1, y1 = coordinates c

  @cache[c] ||= @canvas.extract(x0, y0, x1, y1)
end

#coordinates(c) ⇒ Object

Raises:

  • (ArgumentError)


26
27
28
29
30
31
32
33
34
35
# File 'lib/png/font.rb', line 26

def coordinates c
  i = LETTERS.index c

  raise ArgumentError, "Can't find #{c.inspect}" unless i

  x = (i % 26) * width
  y = (3 - (i / 26)) * height # start from the top (3rd row)

  return x, y, x+width-1, y+height-1
end