Sha256: 95424ac7d0dd2cd782285ab6a3ad698dd103cfcb4a1e4871fa7ba213aeae9b5a

Contents?: true

Size: 1.4 KB

Versions: 3

Compression:

Stored size: 1.4 KB

Contents

module Text2Path

  class Converter

    attr_accessor :text, :font

    def initialize( text, font, opt={} )
      @text = text
      @font = font
      @opt  = opt
    end

    def to_svg
      paths = to_paths
        %Q{<?xml version="1.0" standalone="no"?>} <<
        <<-SVG
          <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
          <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
            <g>#{paths.map {|p| path_element(p) }.join("\n") }</g>
          </svg>
        SVG
      
    end

    def to_paths
      @advance_x = 0
      @text.each_char.map do |letter|
        letter_to_path( letter )
      end.compact
    end

    def letter_to_path( lt )
      glyph = @font.glyph( lt )
      scale = font_size / @font.units_per_em

      if glyph.empty?
        @advance_x += glyph.horiz_adv_x * scale
        nil
      else
        SvgPath.parse( glyph.path ) do |path|
          path.scale scale, -scale
          # TODO: support other text directions
          path.translate advance_x, @font.default_glyph_height * scale
          @advance_x += glyph.horiz_adv_x * scale
        end
      end
    end

    private

      def path_element( path )
        %Q{<path d="#{path.to_command}" />}
      end

      def advance_x
        @advance_x
      end

      def font_size
        @font_size ||= @opt[:font_size] || font.units_per_em
      end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
text2path-0.0.4 lib/text2path/converter.rb
text2path-0.0.2 lib/text2path/converter.rb
text2path-0.0.1 lib/text2path/converter.rb