Module: TkImageMap::Utils

Defined in:
lib/drx/tk/imagemap.rb

Overview

class ImageMap

Class Method Summary collapse

Class Method Details

.parse_imap(filepath) ⇒ Object

Parses an HTML image map.



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/drx/tk/imagemap.rb', line 215

def self.parse_imap(filepath)
  hotspots = []
  require 'rexml/document'
  doc = REXML::Document.new(File.open(filepath))
  doc.root.elements.each do |elt|
    if elt.is_a? REXML::Element and elt.name == 'area'
      attrs  = elt.attributes
      url    = attrs['href']
      coords = attrs['coords'].split(/,|\s+/).map{|c|c.to_i}  # @todo: A circle's radius can be a percent.
      case attrs['shape']
      when 'poly';
        if args = to_oval(coords)
          hotspots << {
            :args => args,
            :class => TkcOval,
            :url => url,
          }
        else
          hotspots << {
            :args => coords,
            :class => TkcPolygon,
            :url => url,
          }
        end
      when 'rect';
        hotspots << {
          :args => coords,
          :class => TkcRectangle,
          :url => url,
        }
      when 'circle';
        cx, cy, radius = coords
        hotspots << {
          :args => [cx - radius, cy - radius, cx + radius, cy + radius],
          :class => TkcOval,
          :url => url,
        }
      else raise "I don't support shape '#{attrs['shape']}'"
      end
    end
  end
  return hotspots
end

.to_oval(coords) ⇒ Object

DOT outputs oval elements as polygons with many many sides. Since Tk doesn’t draw them well, we convert such polygons to ovals.



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/drx/tk/imagemap.rb', line 193

def self.to_oval(coords)
  require 'enumerator'
  #points = coords.each_slice(2).to_a # Doesn't work for older 1.8's.
  points = coords.enum_for(:each_slice, 2).to_a
  if points.size < 10
    # If there are few sides, we assume it's a real polygon.
    return nil
  end
  # Alas, Ruby 1.8.6 doesn't have #minmax
  xs = points.map {|p| p[0]}
  ys = points.map {|p| p[1]}
  x_min, x_max = xs.min, xs.max
  y_min, y_max = ys.min, ys.max
  # @todo: try to figure out if the points trace a circle?
  #center_x = x_min + (x_max - x_min) / 2.0
  #center_y = y_min + (y_max - y_min) / 2.0
  #points.each do |x,y|
  #end
  return [x_min, y_min, x_max, y_max]
end