spritesheet.dart 2.53 KB
Newer Older
1
part of flutter_sprites;
2 3 4 5 6 7 8 9 10

/// A sprite sheet packs a number of smaller images into a single large image.
///
/// The placement of the smaller images are defined by a json file. The larger image and json file is typically created
/// by a tool such as TexturePacker. The [SpriteSheet] class will take a reference to a larger image and a json string.
/// From the image and the string the [SpriteSheet] creates a number of [Texture] objects. The names of the frames in
/// the sprite sheet definition are used to reference the different textures.
class SpriteSheet {

11
  ui.Image _image;
Hixie's avatar
Hixie committed
12
  Map<String, Texture> _textures = new Map<String, Texture>();
13 14 15 16 17 18 19 20 21

  /// Creates a new sprite sheet from an [_image] and a sprite sheet [jsonDefinition].
  ///
  ///     var mySpriteSheet = new SpriteSheet(myImage, jsonString);
  SpriteSheet(this._image, String jsonDefinition) {
    assert(_image != null);
    assert(jsonDefinition != null);

    JsonDecoder decoder = new JsonDecoder();
22
    Map<dynamic, dynamic> file = decoder.convert(jsonDefinition);
23 24
    assert(file != null);

25
    List<dynamic> frames = file["frames"];
26

27
    for (Map<dynamic, dynamic> frameInfo in frames) {
28 29 30 31 32 33 34 35
      String fileName = frameInfo["filename"];
      Rect frame = _readJsonRect(frameInfo["frame"]);
      bool rotated = frameInfo["rotated"];
      bool trimmed = frameInfo["trimmed"];
      Rect spriteSourceSize = _readJsonRect(frameInfo["spriteSourceSize"]);
      Size sourceSize = _readJsonSize(frameInfo["sourceSize"]);
      Point pivot = _readJsonPoint(frameInfo["pivot"]);

36
      Texture texture = new Texture._fromSpriteFrame(_image, fileName, sourceSize, rotated, trimmed, frame,
37 38 39 40 41
        spriteSourceSize, pivot);
      _textures[fileName] = texture;
    }
  }

42
  Rect _readJsonRect(Map<dynamic, dynamic> data) {
43 44 45 46 47 48 49 50
    num x = data["x"];
    num y = data["y"];
    num w = data["w"];
    num h = data["h"];

    return new Rect.fromLTRB(x.toDouble(), y.toDouble(), (x + w).toDouble(), (y + h).toDouble());
  }

51
  Size _readJsonSize(Map<dynamic, dynamic> data) {
52 53 54 55 56 57
    num w = data["w"];
    num h = data["h"];

    return new Size(w.toDouble(), h.toDouble());
  }

58
  Point _readJsonPoint(Map<dynamic, dynamic> data) {
59 60 61 62 63 64 65 66 67
    num x = data["x"];
    num y = data["y"];

    return new Point(x.toDouble(), y.toDouble());
  }

  /// The image used by the sprite sheet.
  ///
  ///     var spriteSheetImage = mySpriteSheet.image;
68
  ui.Image get image => _image;
69 70 71 72 73 74

  /// Returns a texture by its name.
  ///
  ///     var myTexture = mySpriteSheet["example.png"];
  Texture operator [](String fileName) => _textures[fileName];
}