rubylibgosu

Centering text in Gosu


I've been having trouble centering text in the Gosu library to the absolute middle of the screen.

require 'gosu'

class GameWindow < Gosu::Window
  def initialize (width=800, height=600, fullscreen=false)
    super
    self.caption = 'Hello'
    @message = Gosu::Image.from_text(
        self, 'HELLO WORLD', Gosu.default_font_name, 45)
  end

  def draw
    @message.draw(377.5,277.5,0)
  end
end

window = GameWindow.new
window.show 


My first approach was to take the height of the screen, subtract it by the height of the text 45, and then divide by 2. Now that seemed to work when aligning vertically.

enter image description here

However, horizontally is a different story...It seems to be taking the top left corner of the text and centering it which I expected it to do, instead of the middle of the text.

enter image description here

Anyone got a formula for this ? I tried a whole bunch of things, and only came close.


Solution

  • class GameWindow < Gosu::Window
      def initialize (width=800, height=600, fullscreen=false)
        super
        self.caption = 'Hello'
        @message = Gosu::Image.from_text(
            self, 'HELLO WORLD', Gosu.default_font_name, 45)
      end
    
      def draw
        @message.draw(377.5,277.5,0)
      end
    end
    

    Your @message is an instance of Gosu::Image

    As far as I can see, the class has a method that allows you to align the image's rotational center to a specified point, draw_rot

    Using draw_rot instead of draw should work for you once you've found the center of the frame.