sprite_trim

Script for GM:Studio.
Remove the pixels with alpha 0 from the borders

Returns a new sprite or -1 for error.

Arguments

  • sprite : the sprite to trim
  • subimg : the frame of the sprite

Returns : sprite

Source code

  1. ///sprite_trim(sprite, subimg)
  2.  
  3. if(!sprite_exists(argument0))
  4.     return -1;
  5.  
  6. var w = sprite_get_width(argument0);
  7. var h = sprite_get_height(argument0);
  8. var xo = sprite_get_xoffset(argument0);
  9. var yo = sprite_get_yoffset(argument0);
  10. var s = surface_create(w, h);
  11.  
  12. surface_set_target(s);
  13. draw_clear_alpha(0, 0);
  14. draw_sprite(argument0, argument1, xo, yo);
  15. surface_reset_target();
  16.  
  17.  
  18.  
  19. var buf = buffer_create(w * h * 4, buffer_fixed, 4); 
  20. buffer_get_surface(buf, s, 0, 0, 0);
  21.  
  22. var xx, yy, pixel, a;
  23.  
  24. var left = 0, top = 0, right = 0, bottom = 0;
  25.  
  26. //left
  27. for(xx = 0; xx < w; xx++)
  28. {   
  29.     for(yy = 0; yy < h; yy++)
  30.     {
  31.         pixel = buffer_peek(buf, (xx + yy * w) * 4, buffer_u32);
  32.         a = (pixel >> 24) & 255;
  33.         if(a != 0)
  34.             break;
  35.     }
  36.     if(a != 0)
  37.         break;
  38.     else
  39.         left++;
  40. }
  41.  
  42. //top
  43. for(yy = 0; yy < h; yy++)
  44. {
  45.     for(xx = 0; xx < w; xx++)
  46.     {   
  47.         pixel = buffer_peek(buf, (xx + yy * w) * 4, buffer_u32);
  48.         a = (pixel >> 24) & 255;
  49.         if(a != 0)
  50.             break;
  51.     }
  52.     if(a != 0)
  53.         break;
  54.     else
  55.         top++;
  56. }
  57.  
  58. //right
  59. for(xx = w-1; xx >= 0; xx--)
  60. {   
  61.     for(yy = 0; yy < h; yy++)
  62.     {
  63.         pixel = buffer_peek(buf, (xx + yy * w) * 4, buffer_u32);
  64.         a = (pixel >> 24) & 255;
  65.         if(a != 0)
  66.             break;
  67.     }
  68.     if(a != 0)
  69.         break;
  70.     else
  71.         right++;
  72. }
  73.  
  74. //bottom
  75. for(yy = h-1; yy >= 0; yy--)
  76. {
  77.     for(xx = 0; xx < w; xx++)
  78.     {   
  79.         pixel = buffer_peek(buf, (xx + yy * w) * 4, buffer_u32);
  80.         a = (pixel >> 24) & 255;
  81.         if(a != 0)
  82.             break;
  83.     }
  84.     if(a != 0)
  85.         break;
  86.     else
  87.         bottom++;
  88. }
  89.  
  90. buffer_delete(buf);
  91. surface_free(s)
  92. return sprite_create_from_surface(s, left, top, w-left-right, h-top-bottom, 0, 0, xo-left, yo-top);
  93.