twolfson/spritesmith

Is it possible to have x amount of images per row?

Opened this issue · 3 comments

My use-case is a little bit weird, I know.
Let's start pointing out that all the images are the same size, the sprites should have like 12 (even tho it's not always 12...) of them per row and a padding around them (you know, like CSS' padding works), not between them.
Is there a way to do that? I looked through the documentation but couldn't find anything helpful although I found that the images can be placed in the order I want to, and that's a huge +1.

I think I can solve the first problem in two different ways:

  1. setting a maximum amount of images for every row
  2. setting a maximum width of the output image

But is it possible? 🤔

Well, after reading it again I think it's somehow related to #55.
Sorry for the duplicate, I guess 😛

I think #55 is a slightly different problem; they want to generate multiple spritesheets whereas you mostly want the image count per row to be constrained but don't care about height

The current spritesmith implementation supports this by its algorithm parameter. We'll need to define a custom algorithm which places items left to right and then wraps them:

https://github.com/Ensighten/spritesmith/tree/3.3.0#algorithms

https://github.com/Ensighten/spritesmith/tree/3.3.0#algorithm

https://github.com/twolfson/layout/tree/2.2.0#custom-algorithms

Example algorithm: https://github.com/twolfson/layout/blob/2.2.0/lib/algorithms/left-right.algorithm.js

var layout = require('layout');

var ITEM_COUNT_PER_ROW = 12;
var ROW_HEIGHT = 24; // px

layout.addAlgorithm('left-right-bounded', {
  sort: function () {
    // Do nothing, assume sorted
  },
  placeItems: function () {
    // Iterate over each of the items
    var x;
    items.forEach(function (item, i) {
      // Determine our row and base offset
      var row_index = Math.floor(i / ITEM_COUNT_PER_ROW);
      if (i % ITEM_COUNT_PER_ROW === 0) {
        x = 0;
      }

      // Update the x to the current width
      // DEV: We could make ROW_HEIGHT generic but this using a constant is easier
      item.x = x;
      item.y = row_index * ROW_HEIGHT;

      // Increment the x by the item's width
      x += item.width;
    });

    // Return the items
    return items;
  },
});

// Run spritesmith with our algorithm
{
  algorithm: 'left-right-bounded'
}

Oh, nice!
I didn't realize that algorithms could be used like that, thank you very much 😃