From 266e85ce7cb75d71fc29717ece6d0552b392d630 Mon Sep 17 00:00:00 2001 From: feroult Date: Tue, 14 Nov 2017 14:34:21 -0200 Subject: [PATCH] box fit for sprite components --- lib/component.dart | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/lib/component.dart b/lib/component.dart index faf3e3128..4fe43c758 100644 --- a/lib/component.dart +++ b/lib/component.dart @@ -1,20 +1,25 @@ -import 'dart:ui'; import 'dart:math'; +import 'dart:ui'; + +import 'package:flutter/painting.dart'; import 'flame.dart'; abstract class Component { void update(double t); + void render(Canvas c); } abstract class PositionComponent extends Component { - double x, y, angle; + double x = 0.0, + y = 0.0, + angle = 0.0; double angleBetween(PositionComponent c) { - return (atan2(c.x - this.x, this.y - c.y) - PI/2) % (2*PI); + return (atan2(c.x - this.x, this.y - c.y) - PI / 2) % (2 * PI); } double distance(PositionComponent c) { @@ -28,22 +33,33 @@ abstract class SpriteComponent extends PositionComponent { double width, height; Image image; - final Paint paint = new Paint()..color = new Color(0xffffffff); + final Paint paint = new Paint() + ..color = new Color(0xffffffff); - SpriteComponent.square(double size, String imagePath) : this.rectangle(size, size, imagePath); + SpriteComponent.square(double size, String imagePath) + : this.rectangle(size, size, imagePath); SpriteComponent.rectangle(this.width, this.height, String imagePath) { - Flame.images.load(imagePath).then((image) { this.image = image; }); + Flame.images.load(imagePath).then((image) { + this.image = image; + }); } render(Canvas canvas) { canvas.translate(x, y); - canvas.rotate(PI/2 + angle); - canvas.translate(-width/2, -height/2); + canvas.rotate(angle); // TODO: rotate around center if (image != null) { - Rect src = new Rect.fromLTWH(0.0, 0.0, image.width.toDouble(), image.height.toDouble()); - Rect dst = new Rect.fromLTWH(0.0, 0.0, width, height); - canvas.drawImageRect(image, src, dst, paint); + final Rect outputRect = new Rect.fromLTWH(0.0, 0.0, width, height); + + final Size imageSize = new Size( + image.width.toDouble(), image.height.toDouble()); + final FittedSizes sizes = applyBoxFit( + BoxFit.fill, imageSize, outputRect.size); + final Rect inputSubrect = Alignment.center.inscribe( + sizes.source, Offset.zero & imageSize); + final Rect outputSubrect = Alignment.center.inscribe( + sizes.destination, outputRect); + canvas.drawImageRect(image, inputSubrect, outputSubrect, paint); } }