Image Example

require 'gosu'

class ImageExample < Gosu::Window
	def initialize
		super 640, 480
		self.caption = "Image Example"
		@ball = Gosu::Image.new("./ball.png")
	end
	
	def draw
		@ball.draw( 100, 100, 0 )
	end
end

window = ImageExample.new.show
Note: If you don’t have an image, I’ve included one in the snippet repository.

Like most resources in Gosu, using images comes in two parts: Creating them and drawing them.

The simplest way of creating an image is to simply pass in a path to an image file during creation (like I am). However, you can customize it further by passing in additional arguments. Some arguments of note:

:retro => true will tell Gosu to not smooth our image out if it gets stretched or scrunched. This is helpful for maintaining a pixelated effect.

:rect => [x, y, width, height] allows us to create an image out of a part of an image instead of a whole thing. Helpful if you’re working with a spritesheet.

:tileable => true is similar to :retro except it tells Gosu to only avoid smoothing the edges. This is helpful for tiles where the edges need to line up to form a pattern.

Line 11 draws our image at a given set of XYZ coordinates. X is left-right, Y is top-down, but why the Z coordinate in a 2D game? The reason is that when two images are drawn on a 2D plane, we have to decide which one gets drawn on top. We could do this using the order we draw (i.e. last image ends up on top), but the Z coordinate makes this management easier by assigning images to “layers” (highest Z value ends up on top).

Like the constructor, this method can be extended with a bunch of additional parameters to create more interesting effects:

draw(x, y, z, scale_x = 1, scale_y = 1, color = 0xff_ffffff, mode = :default)
  • x: The X-Coordinate of your image (the upper side)
  • y: The Y-Coordinate of your image(the left side)
  • z: The Z-Index or Z-Order which determines which images are drawn on top
  • scale_x: Factor that gets multiplied against the width of your image to grow or shrink it (e.g. 0.5 halves the image size, 2 doubles it, 1 keeps it the same)
  • scale_y: Factor that gets multiplied against the height of your image to grow or shrink it (e.g. 0.5 halves the image size, 2 doubles it, 1 keeps it the same)
  • color: Shades the image with the color specified (as a hexidecimal value)
  • mode: Determines how the image is “blended” with the images underneath it.

You can also use draw_rot() to rotate the image (in degrees). You can find more details on this and the other Image methods here in the Gosu documentation!