Class: Ruby2D::Font

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

Overview

Font represents a single typeface in a specific size and style. Use Font.load to load/retrieve a Font instance by path, size and style.

Constant Summary collapse

FONT_CACHE_LIMIT =
100

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, size, style = nil) ⇒ Font

Private constructor, called internally using Font.send(:new,…)



136
137
138
# File 'lib/ruby2d/font.rb', line 136

def initialize(path, size, style = nil)
  @ttf_font = Font.ext_load(path.to_s, size, style.to_s)
end

Instance Attribute Details

#ttf_fontObject (readonly)

Returns the value of attribute ttf_font.



12
13
14
# File 'lib/ruby2d/font.rb', line 12

def ttf_font
  @ttf_font
end

Class Method Details

.allObject

List all fonts, names only



35
36
37
# File 'lib/ruby2d/font.rb', line 35

def all
  all_paths.map { |path| path.split('/').last.chomp('.ttf').downcase }.uniq.sort
end

.defaultObject

Get full path to the default font



47
48
49
50
51
52
53
# File 'lib/ruby2d/font.rb', line 47

def default
  if all.include? 'arial'
    path 'arial'
  else
    all_paths.first
  end
end

.load(path, size, style = nil) ⇒ Font

Return a font by path, size and style, loading the font if not already in the cache.

Parameters:

  • path (#to_s)

    Full path to the font file

  • size (Numeric)

    Size of font to setup

  • style (String) (defaults to: nil)

    Font style

Returns:

Raises:



25
26
27
28
29
30
31
32
# File 'lib/ruby2d/font.rb', line 25

def load(path, size, style = nil)
  path = path.to_s
  raise Error, "Cannot find font file `#{path}`" unless File.exist? path

  (@loaded_fonts[[path, size, style]] ||= Font.send(:new, path, size, style)).tap do |_font|
    @loaded_fonts.shift if @loaded_fonts.size > FONT_CACHE_LIMIT
  end
end

.path(font_name) ⇒ String?

Find a font file path from its name, if it exists in the platforms list of fonts

Returns:

  • (String)

    full path if font_name is known

  • (nil)

    if font_name is unknown



42
43
44
# File 'lib/ruby2d/font.rb', line 42

def path(font_name)
  all_paths.find { |path| path.downcase.include?(font_name) }
end