Last Updated: February 25, 2016
·
849
· jonasnielsen

RubyMotion NSView with gradient background

class GradientView < NSView

  def initWithFrame rect
    super.tap do
      @starting_color = NSColor.colorWithCalibratedWhite(1.0, alpha: 1.0)
      @ending_color = nil
      @angle = 270
    end
  end

  def drawRect rect
    if @starting_color && @ending_color
      gradient = NSGradient.alloc.initWithStartingColor(@starting_color, endingColor: @ending_color)
      gradient.drawInRect(self.bounds, angle: @angle)
    else
      @starting_color.set
      NSRectFill(rect)
    end
  end

  def starting_color= ns_color
    @starting_color = ns_color
    self.setNeedsDisplay(true)
  end

  def ending_color= ns_color
    @ending_color = ns_color
    self.setNeedsDisplay(true)
  end

  def angle= int
    @angle = int
    self.setNeedsDisplay(true)
  end
end

Inspired from this gist