Refactoring assets loading on Flame

This commit is contained in:
Erick Zanardo
2020-09-20 14:45:07 -03:00
parent 113e0db074
commit 585b440d0b
11 changed files with 216 additions and 117 deletions

View File

@ -1,7 +1,5 @@
import 'dart:ui';
import 'dart:async';
import 'flame.dart';
import 'position.dart';
import 'palette.dart';
@ -11,67 +9,24 @@ class Sprite {
Rect src;
Sprite(
String fileName, {
double x = 0.0,
double y = 0.0,
double width,
double height,
}) {
Flame.images.load(fileName).then((img) {
width ??= img.width.toDouble();
height ??= img.height.toDouble();
image = img;
src = Rect.fromLTWH(x, y, width, height);
});
}
Sprite.fromImage(
this.image, {
double x = 0.0,
double y = 0.0,
double width,
double height,
}) {
}) : assert(image != null, "image can't be null") {
width ??= image.width.toDouble();
height ??= image.height.toDouble();
src = Rect.fromLTWH(x, y, width, height);
}
static Future<Sprite> loadSprite(
String fileName, {
double x = 0.0,
double y = 0.0,
double width,
double height,
}) async {
final Image image = await Flame.images.load(fileName);
return Sprite.fromImage(
image,
x: x,
y: y,
width: width,
height: height,
);
}
bool loaded() {
return image != null && src != null;
}
double get _imageWidth => image.width.toDouble();
double get _imageHeight => image.height.toDouble();
Position get originalSize {
if (!loaded()) {
return null;
}
return Position(_imageWidth, _imageHeight);
}
Position get originalSize => Position(_imageWidth, _imageHeight);
Position get size {
return Position(src.width, src.height);
}
Position get size => Position(src.width, src.height);
/// Renders this Sprite on the position [p], scaled by the [scale] factor provided.
///
@ -80,18 +35,12 @@ class Sprite {
/// If not loaded, does nothing.
void renderScaled(Canvas canvas, Position p,
{double scale = 1.0, Paint overridePaint}) {
if (!loaded()) {
return;
}
renderPosition(canvas, p,
size: size.times(scale), overridePaint: overridePaint);
}
void renderPosition(Canvas canvas, Position p,
{Position size, Paint overridePaint}) {
if (!loaded()) {
return;
}
size ??= this.size;
renderRect(canvas, Position.rectFrom(p, size),
overridePaint: overridePaint);
@ -99,9 +48,6 @@ class Sprite {
void render(Canvas canvas,
{double width, double height, Paint overridePaint}) {
if (!loaded()) {
return;
}
width ??= size.x;
height ??= size.y;
renderRect(canvas, Rect.fromLTWH(0.0, 0.0, width, height),
@ -114,9 +60,6 @@ class Sprite {
/// If the asset is not yet loaded, it does nothing.
void renderCentered(Canvas canvas, Position p,
{Position size, Paint overridePaint}) {
if (!loaded()) {
return;
}
size ??= this.size;
renderRect(canvas,
Rect.fromLTWH(p.x - size.x / 2, p.y - size.y / 2, size.x, size.y),
@ -124,9 +67,6 @@ class Sprite {
}
void renderRect(Canvas canvas, Rect dst, {Paint overridePaint}) {
if (!loaded()) {
return;
}
canvas.drawImageRect(image, src, dst, overridePaint ?? paint);
}
}