Sha256: 867b6eee3806d4731715b507744e44ce4f6f20f68d623c388fb4e8a6d8dda385

Contents?: true

Size: 1.73 KB

Versions: 4

Compression:

Stored size: 1.73 KB

Contents

module QRCoder
  module Renderers
    class SVG
      class << self
        # Render the SVG from the qrcode string provided from the RQRCode gem
        #   Options:
        #   offset - Padding around the QR Code (e.g. 10)
        #   unit   - How many pixels per module (Default: 11)
        #   fill   - Background color (e.g "ffffff" or :white)
        #   color  - Foreground color for the code (e.g. "000000" or :black)

        def render(qrcode, options={})
          offset  = options[:offset].to_i || 0
          color   = options[:color]       || "000"
          unit    = options[:unit]        || 11

          # height and width dependent on offset and QR complexity
          dimension = (qrcode.module_count*unit) + (2*offset)

          xml_tag   = %{<?xml version="1.0" standalone="yes"?>}
          open_tag  = %{<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" width="#{dimension}" height="#{dimension}">}
          close_tag = "</svg>"

          result = []
          qrcode.modules.each_index do |c|
            tmp = []
            qrcode.modules.each_index do |r|
              y = c*unit + offset
              x = r*unit + offset

              next unless qrcode.is_dark(c, r)
              tmp << %{<rect width="#{unit}" height="#{unit}" x="#{x}" y="#{y}" style="fill:##{color}"/>}
            end 
            result << tmp.join
          end
          
          if options[:fill]
            result.unshift %{<rect width="#{dimension}" height="#{dimension}" x="0" y="0" style="fill:##{options[:fill]}"/>}
          end
          
          svg = [xml_tag, open_tag, result, close_tag].flatten.join("\n")
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
qrcoder-0.1.3 lib/qrcoder/renderers/svg.rb
qrcoder-0.1.2 lib/rqrcoder/renderers/svg.rb
qrcoder-0.1.1 lib/rqrcoder/renderers/svg.rb
qrcoder-0.1 lib/rqrcoder/renderers/svg.rb