Skip to content

Instantly share code, notes, and snippets.

@arbales
Created September 18, 2011 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arbales/1224562 to your computer and use it in GitHub Desktop.
Save arbales/1224562 to your computer and use it in GitHub Desktop.
class Array; def sum; inject( nil ) { |sum,x| sum ? sum+x : x }; end; end
require 'ruby-processing'
class PieChart
include Processing::Proxy
include Math
attr_accessor :colors
def initialize(data, options)
# Setup coordinates for display.
@x = options[:coords][:x]
@y = options[:coords][:y]
@radius = options[:radius]
@data = data
@data_sum = 0.0
@duration = 20
@current = 0
@rotation = random(PI * 2, PI * 4)
@drawRadius = 0
@dataRad = []
@data_sum = @data.sum
@data.each do |item|
@dataRad << item / @data_sum * 360
end
@font = createFont "LeagueGothic", 40
end
def render
@current += (@duration - @current) * 0.1
@rotation += ((-PI / 2) - @rotation) * 0.05
@drawRadius += (@radius - @drawRadius) * 0.2
displayPercentage = (@data[0] / @data_sum * 100 * @current / @duration).to_i
pushMatrix
translate @x, @y
rotateZ @rotation
lastAng = 0
@dataRad.each do |i|
r = radians(i) * @current / @duration
fill 100, 10
noStroke
arc 0, 0, @drawRadius * 2 + 10, @drawRadius * 2 + 10, lastAng, lastAng + r
lastAng += r
end
lastAng = 0
@dataRad.each_with_index do |measurement, index|
r = radians(measurement) * @current / @duration
if index == 0
fill color(hue(@colors[0]), saturation(@colors[0]), 80)
else
fill color(hue(@colors[0]), saturation(@colors[0]), 40)
end
noStroke
arc(0, 0, @drawRadius*2, @drawRadius*2, lastAng, lastAng + r)
lastAng += r
end
rotateZ(-@rotation)
textAlign CENTER
textFont @font, 48
fill 100
text "#{displayPercentage}%", 0, 16
popMatrix
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment