Ruby Gosu:如何将实际的 Window/Screen 保存到图像文件中?

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

我正在尝试制作 Window/Screen 实际状态的屏幕截图功能。如何使用 Ruby Gosu 实现此目的?

使用Gosu的Gosu.render方法

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

如果需要,您也可以使用不带 window 的 Gosu.render:

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")