Nineslice GML Script

Here’s a handy script I use all the time. It’s a draw function that uses a sprite with 9 frames, each one representing a different area of a background, button, or object, and scales it to fit the size of the area you want.

Mainly, I use it to draw dynamic sized text areas.

The sprite it’s expecting looks like this:

Download Example Sprite

The actual sprite size can vary as much as you want, as long as you follow the image order shown.

  1. Top left
  2. Top middle
  3. Top right
  4. Middle left
  5. Middle middle
  6. Middle right
  7. Bottom left
  8. Bottom middle
  9. Bottom right

///draw_nineslice(x1, y1, x2, y2, sprite);
///@param x1
///@param y1
///@param x2
///@param y2
///@param sprite

//Set vars
var x1 = argument0;
var y1 = argument1;
var x2 = argument2;
var y2 = argument3;
var sprite = argument4;

var spriteWidth = sprite_get_width(sprite);
var spriteHeight = sprite_get_height(sprite);

var innerWidth = abs((x2 - x1) - (spriteWidth * 2));
var innerHeight = abs((y2 - y1) - (spriteHeight * 2));

//set vars and raw top
var topLeftX = x1;
var topY = y1;
var topMiddleX = topLeftX + spriteWidth;
var topRightX = topMiddleX + innerWidth;

draw_sprite_stretched(sprite, 1, topMiddleX - 1, topY, innerWidth + 2, spriteHeight);
draw_sprite(sprite, 0, topLeftX, topY);
draw_sprite(sprite, 2, topRightX, topY);

//set vars and draw mid
var centerLeftX = x1;
var centerY = y1 + spriteHeight;
var centerMiddleX = centerLeftX + spriteWidth;
var centerRightX = centerMiddleX + innerWidth;

draw_sprite_stretched(sprite, 3, centerLeftX, centerY, spriteWidth, innerHeight);
draw_sprite_stretched(sprite, 4, centerMiddleX, centerY, innerWidth, innerHeight);
draw_sprite_stretched(sprite, 5, centerRightX, centerY, spriteWidth, innerHeight);

//set vars and draw bottom
var bottomLeftX = x1;
var bottomY = y1 + spriteHeight + innerHeight;
var bottomMiddleX = bottomLeftX + spriteWidth;
var bottomRightX = bottomMiddleX + innerWidth;

draw_sprite(sprite, 6, bottomLeftX, bottomY);
draw_sprite_stretched(sprite, 7, bottomMiddleX, bottomY, innerWidth, spriteHeight);
draw_sprite(sprite, 8, bottomRightX, bottomY);

Very useful for resizable windows, background, buttons, and objects like rugs that have a tiled center and unique edges.

Leave a Reply

Your email address will not be published. Required fields are marked *