-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsvg_parser.rb
73 lines (59 loc) · 1.62 KB
/
svg_parser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
70
71
72
73
#!/usr/bin/env ruby
require 'hpricot'
require 'gosu' rescue nil
require File.join(File.dirname(__FILE__), "points")
#
# SVGParser - Reads out info from a SVGfile
#
# Currently it it reads out the coordinates for
# Coordinates for a certain id is stored using Points-class which in turn enables .to_chipmunk, .normalize! etc
#
#
class SVGParser
attr_reader :filename, :paths
def initialize(filename)
@filename = filename
@fh = @filename if @filename.is_a? File
@fh = open(@filename) if @filename.is_a? String
@paths = Hash.new
@rects = Hash.new
@doc = Hpricot(@fh)
end
def inspect; @doc; end
def to_s; @doc.to_s; end
#
# Get points for a "path" (inkscape Shift+F6) with a certain id
#
def rect(id)
points = Points.new
if rect = @doc.at("//g rect[@id='#{id.to_s}']")
#
# Generate all the points in a rectangle
#
top_left = [rect[:x].to_f, rect[:y].to_f]
top_right = [rect[:x].to_f + rect[:width].to_f, rect[:y].to_f ]
bottom_right = [rect[:x].to_f + rect[:width].to_f, rect[:y].to_f + rect[:height].to_f ]
bottom_left = [rect[:x].to_f, rect[:y].to_f + rect[:height].to_f ]
points << top_left
points << bottom_left
points << bottom_right
points << top_right
end
@rects[id.to_sym] = points
end
#
# Get points for a "path" (inkscape Shift+F6) with a certain id
#
def path(id)
points = Points.new
if path = @doc.at("//g path[@id='#{id.to_s}']")
path[:d].split(" ").each do |point|
x, y = point.split(",")
points << [x.to_f, y.to_f] if x and y
end
else
raise "Cant find item with id=#{id.to_s}"
end
@paths[id.to_sym] = points
end
end