Class: PixelFont

Inherits:
Object
  • Object
show all
Defined in:
src/ruby/include/cypher.rb

Class Method Summary collapse

Class Method Details

.draw_text(png, s, font, color, options = {}) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'src/ruby/include/cypher.rb', line 71

def self.draw_text(png, s, font, color, options = {})
    @@cypher_fonts ||= {}
    @@cypher_fonts[font] ||= load_font("fonts/ucs/#{font}.bdf")
    options[:x] ||= 0
    options[:y] ||= 0
    options[:scale] ||= 1
    dx = 0
    s.each_char do |c|
        glyph = @@cypher_fonts[font][c.ord]
        if glyph
            w = ((((glyph[:width] - 1) >> 3) + 1) << 3) - 1
            (0...glyph[:height]).each do |iy|
                (0...glyph[:width]).each do |ix|
                    if (((glyph[:bitmap][iy] >> (w - ix)) & 1) == 1)
                        (0...options[:scale]).each do |oy|
                            (0...options[:scale]).each do |ox|
                                png.set_pixel_if_within_bounds(options[:x] + (ix + dx) * options[:scale] + ox, options[:y] + iy * options[:scale] + oy, color)
                            end
                        end
                    end
                end
            end
            dx += glyph[:width]
        end
    end
end

.load_font(path) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'src/ruby/include/cypher.rb', line 42

def self.load_font(path)
    STDERR.puts "Loading font from #{path}..."
    font = {}
    File.open(path) do |f|
        char = nil
        f.each_line do |line|
            if line[0, 9] == 'STARTCHAR'
                char = {}
            elsif line[0, 8] == 'ENCODING'
                char[:encoding] = line.sub('ENCODING ', '').strip.to_i
            elsif line[0, 7] == 'ENDCHAR'
                font[char[:encoding]] = char
                char = nil
            elsif line[0, 3] == 'BBX'
                parts = line.split(' ')
                char[:width] = parts[1].to_i
                char[:height] = parts[2].to_i
            elsif line[0, 6] == 'BITMAP'
                char[:bitmap] = []
            else
                if char && char[:bitmap]
                    char[:bitmap] << line.to_i(16)
                end
            end
        end
    end
    font
end

.text_width(s, font, options = {}) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
# File 'src/ruby/include/cypher.rb', line 98

def self.text_width(s, font, options = {})
    @@cypher_fonts ||= {}
    @@cypher_fonts[font] ||= load_font("fonts/ucs/#{font}.bdf")
    width = 0
    s.each_char do |c|
        glyph = @@cypher_fonts[font][c.ord]
        if glyph
            width += glyph[:width]
        end
    end
    width
end