rubylibgosu

Ruby Gosu: how can I save the actual Window/Screen in an image file?


I am trying make a screenshot functionality of the actual state of the Window/Screen. How can I achieve this using Ruby Gosu?


Solution

  • Use Gosu's Gosu.render method

    require "gosu"
    
    class Window < Gosu::Window
      def initialize(*args)
        super
      end
      
      def draw
        Gosu.draw_rect(100, 100, 100, 100, Gosu::Color::YELLOW)
      end
      
      def button_down(id)
        render("screenshot.png") if id == Gosu::KB_F12
      end
      
      def render(filename)
        Gosu.render(600, 600, retro: false) do
          # Put drawing code here, i.e.
          draw
        end.save(filename)
      end
    end
    
    Window.new(600, 600, false).show
    

    You also can use Gosu.render without a window if that is desired:

    require "gosu"
    
    image = Gosu.render(600, 600, retro: false) do
      Gosu.draw_rect(100, 100, 100, 100, Gosu::Color::YELLOW)
    end
    
    image.save("image.png")