sliceIntoFrames method

List<BitmapData> sliceIntoFrames(
  1. num frameWidth,
  2. num frameHeight, {
  3. int? frameCount,
  4. num frameSpacing = 0,
  5. num frameMargin = 0,
})

Returns an array of BitmapData based on this BitmapData's texture.

This function is used to "slice" a spritesheet, tileset, or spritemap into several different frames. All BitmapData's produced by this method are linked to this BitmapData's texture for performance.

The optional frameCount parameter will limit the number of frames generated, in case you have empty frames you don't care about due to the width / height of this BitmapData. If your frames are also separated by space or have an additional margin for each frame, you can specify this with the spacing or margin parameter (in pixel).

Implementation

List<BitmapData> sliceIntoFrames(num frameWidth, num frameHeight,
    {int? frameCount, num frameSpacing = 0, num frameMargin = 0}) {
  final cols =
      (width - frameMargin + frameSpacing) ~/ (frameWidth + frameSpacing);
  final rows =
      (height - frameMargin + frameSpacing) ~/ (frameHeight + frameSpacing);
  final frames = <BitmapData>[];

  frameCount =
      (frameCount == null) ? rows * cols : min(frameCount, rows * cols);

  for (var f = 0; f < frameCount; f++) {
    final x = f % cols;
    final y = f ~/ cols;
    final frameLeft = frameMargin + x * (frameWidth + frameSpacing);
    final frameTop = frameMargin + y * (frameHeight + frameSpacing);
    final rectangle =
        Rectangle<num>(frameLeft, frameTop, frameWidth, frameHeight);
    final bitmapData = BitmapData.fromBitmapData(this, rectangle);
    frames.add(bitmapData);
  }

  return frames;
}