diff --git a/packages/flame/lib/src/sprite.dart b/packages/flame/lib/src/sprite.dart index 413417d9210..fcebff52646 100644 --- a/packages/flame/lib/src/sprite.dart +++ b/packages/flame/lib/src/sprite.dart @@ -101,7 +101,7 @@ class Sprite { final drawSize = size ?? srcSize; final delta = anchor.toVector2()..multiply(drawSize); - final drawRect = (drawPosition + delta).toPositionedRect(drawSize); + final drawRect = (drawPosition - delta).toPositionedRect(drawSize); final drawPaint = overridePaint ?? paint; diff --git a/packages/flame/test/_goldens/sprite_test_1.png b/packages/flame/test/_goldens/sprite_test_1.png new file mode 100644 index 00000000000..2288a1649e8 Binary files /dev/null and b/packages/flame/test/_goldens/sprite_test_1.png differ diff --git a/packages/flame/test/_resources/flame.png b/packages/flame/test/_resources/flame.png new file mode 100644 index 00000000000..2844782bc39 Binary files /dev/null and b/packages/flame/test/_resources/flame.png differ diff --git a/packages/flame/test/_resources/load_image.dart b/packages/flame/test/_resources/load_image.dart new file mode 100644 index 00000000000..4ed1dcd891a --- /dev/null +++ b/packages/flame/test/_resources/load_image.dart @@ -0,0 +1,9 @@ +import 'dart:io'; +import 'dart:ui'; + +Future loadImage(String fileName) async { + final bytes = await File('test/_resources/$fileName').readAsBytes(); + final codec = await instantiateImageCodec(bytes); + final frameInfo = await codec.getNextFrame(); + return frameInfo.image; +} diff --git a/packages/flame/test/sprite_test.dart b/packages/flame/test/sprite_test.dart new file mode 100644 index 00000000000..22d5a302014 --- /dev/null +++ b/packages/flame/test/sprite_test.dart @@ -0,0 +1,50 @@ +import 'dart:ui'; + +import 'package:flame/components.dart'; +import 'package:flame/game.dart'; +import 'package:flame_test/flame_test.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '_resources/load_image.dart'; + +void main() { + group('Sprite', () { + FlameTester(() => FlameGame()).testGameWidget( + 'Render with anchor', + setUp: (game, tester) async { + game.add(MyComponent()..position = Vector2.all(25)); + await game.ready(); + }, + verify: (game, tester) async { + await expectLater( + find.byGame(), + matchesGoldenFile('_goldens/sprite_test_1.png'), + ); + }, + ); + }); +} + +class MyComponent extends PositionComponent { + MyComponent() : super(size: Vector2(200, 400)); + late final Sprite sprite; + + @override + Future onLoad() async { + sprite = Sprite(await loadImage('flame.png')); + } + + @override + void render(Canvas canvas) { + canvas.drawRect( + size.toRect(), + Paint() + ..color = const Color(0xffffffff) + ..style = PaintingStyle.stroke + ..strokeWidth = 2, + ); + // Expected: sprite is rendered in the center of the rect + sprite.render(canvas, position: size / 2, anchor: Anchor.center); + } +}