mirror of
https://github.com/flame-engine/flame.git
synced 2025-11-03 20:36:31 +08:00
Creating spriteAsWidget helper
This commit is contained in:
@ -1,11 +1,17 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flame/animation.dart' as animation;
|
||||
import 'package:flame/sprite.dart';
|
||||
import 'package:flame/flame.dart';
|
||||
import 'package:flame/position.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
void main() => runApp(MyApp());
|
||||
Sprite _sprite;
|
||||
|
||||
void main() async {
|
||||
_sprite = await Sprite.loadSprite('minotaur.png', width: 96, height: 96);
|
||||
runApp(MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
@override
|
||||
@ -65,6 +71,9 @@ class _MyHomePageState extends State<MyHomePage> {
|
||||
animation.Animation.sequenced('minotaur.png', 19,
|
||||
textureWidth: 96.0)),
|
||||
const Text('Neat, hum?'),
|
||||
const Text('By the way, you can also use static sprites as widgets:'),
|
||||
Flame.util.spriteAsWidget(const Size(100, 100), _sprite),
|
||||
const SizedBox(height: 40),
|
||||
const Text('Sprites from Elthen\'s amazing work on itch.io:'),
|
||||
const Text('https://elthen.itch.io/2d-pixel-art-minotaur-sprites'),
|
||||
],
|
||||
|
||||
@ -6,6 +6,7 @@ import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart' as widgets;
|
||||
|
||||
import 'animation.dart';
|
||||
import 'sprite.dart';
|
||||
import 'components/animation_component.dart';
|
||||
import 'game.dart';
|
||||
import 'position.dart';
|
||||
@ -88,4 +89,26 @@ class Util {
|
||||
SimpleGame(AnimationComponent(size.x, size.y, animation)),
|
||||
size: size);
|
||||
}
|
||||
|
||||
/// Returns a regular Flutter widget represeting this sprite, rendered with the specified size.
|
||||
///
|
||||
/// This will create a [CustomPaint] widget using a [CustomPainter] for rendering the [Sprite]
|
||||
/// Be aware that the Sprite must have been loaded, otherwise it can't be rendered
|
||||
widgets.CustomPaint spriteAsWidget(Size size, Sprite sprite) => widgets.CustomPaint(size: size, painter: _SpriteCustomPainter(sprite));
|
||||
}
|
||||
|
||||
class _SpriteCustomPainter extends widgets.CustomPainter {
|
||||
Sprite _sprite;
|
||||
|
||||
_SpriteCustomPainter(this._sprite);
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
if (_sprite.loaded()) {
|
||||
_sprite.render(canvas, size.width, size.height);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(widgets.CustomPainter old) => false;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user