Over a million developers have joined DZone.

Having Rails & Cocoa Play Together

DZone's Guide to

Having Rails & Cocoa Play Together

· ·
Free Resource
// description of your code here
Play a Quartz composition from within a Rails application.

# Render a Quartz Composition ".qtz" file to buffer, as jpeg data
# Written by PLR from Pierlis (http://pierlis.com)
# Use at your own risk, reuse at will.

# Cocoa and the Quartz framework must have been included in config/environment.rb.

class Composition
  # creates a composition from a .qtz file whose path is qtz_path
  def initialize(qtz_path, width = 350, height = 100)
    @qtz = QCComposition.compositionWithFile(qtz_path)
    raise "Can't find a valid composition at “#{qtz_path}”." if @qtz.nil?
    @renderer = QCRenderer.alloc.initOffScreenWithSize_colorSpace_composition(
                        [width, height],
  # renders the composition at time, with parameters, and return the jpeg data.
  def render(time = 0, parameters = {})
    # Only pass in parameters expected by the Qtz composition
    input_keys = @qtz.inputKeys
    parameters.each do |key, value|
      @renderer.setValue_forInputKey(value, key) if input_keys.include? key
    # And render the composition
    rendering_ok = @renderer.renderAtTime_arguments(time, nil)
    raise "Unable to render Quartz Composition" unless rendering_ok == 1
    # now convert the result to jpeg
    bitmapRep = @renderer.createSnapshotImageOfType('NSBitmapImageRep')
    jpegimagedata = bitmapRep.representationUsingType_properties(NSJPEGFileType, 
      {NSImageCompressionFactor => 0.8}

See more on : 

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}