Skip to content

Instantly share code, notes, and snippets.

@katsaii
Last active September 14, 2019 00:44
Show Gist options
  • Save katsaii/5c0ab769f196c917f36cf71f1567c969 to your computer and use it in GitHub Desktop.
Save katsaii/5c0ab769f196c917f36cf71f1567c969 to your computer and use it in GitHub Desktop.
Draws a sprite within a fixed region, resizing where necessary. Maintains the aspect ratio and 'whitespace' of the sprite.
/// @desc Draws a sprite in the middle of some fixed region, scaling where appropriate.
/// @param sprite {Integer} The id of the sprite to draw.
/// @param index {Integer} The image index of the sprite to draw.
/// @param x1 {Integer} The left-most position of the region.
/// @param y1 {Integer} The top-most position of the region.
/// @param x2 {Integer} The right-most position of the region.
/// @param y2 {Integer} The bottom-most position of the region.
/// @author Kat @katsaii
var x1 = argument2 < argument4 ? argument2 : argument4;
var y1 = argument3 < argument5 ? argument3 : argument5;
var x2 = argument4 > argument2 ? argument4 : argument2;
var y2 = argument5 > argument3 ? argument5 : argument3;
var width_max = x2 - x1;
var height_max = y2 - y1;
var uvs = sprite_get_uvs(argument0, argument1);
var width = sprite_get_width(argument0) * uvs[6];
var height = sprite_get_height(argument0) * uvs[7];
var scale = 1;
switch ((width > width_max) << 0 | (height > height_max) << 1) {
case 1 << 0 | 1 << 1:
// choose best scale orientation
var scalex = width_max / width;
var scaley = height_max / height;
scale = min(scalex, scaley);
break;
case 0 << 0 | 1 << 1:
// scale height
scale = height_max / height;
break;
case 1 << 0 | 0 << 1:
// scale width
scale = width_max / width;
break;
}
// actually draw the sprite
width = floor(width * scale);
height = floor(height * scale);
var cx = mean(x2, x1);
var cy = mean(y2, y1);
var left = floor(cx - width * 0.5);
var top = floor(cy - height * 0.5);
var right = left + width;
var bottom = top + height;
draw_sprite_pos(argument0, argument1,
left, top,
right, top,
right, bottom,
left, bottom,
draw_get_alpha());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment