17.4 Using the Flame graphic primitives
import 'dart:async' ;
import 'package:flame/flame.dart' ;
import 'package:flame/game.dart' ;
import 'package:flame/components.dart' ;
import 'package:flutter/material.dart' ;
void main () async {
WidgetsFlutterBinding .ensureInitialized ();
await Flame .device.setPortrait ();
final shapeGame = ShapesExample ();
runApp (GameWidget (game: shapeGame));
}
class ShapesExample extends FlameGame {
@override
Future <void > onLoad () async {
super .onLoad ();
add (RectComponent (size[0 ], size[1 ]));
add (LineComponent (size[0 ], size[1 ]));
add (CircleComponent (size[0 ], size[1 ]));
}
@override
void update (double dt) {
super .update (dt);
}
@override
void render (Canvas canvas) {
super .render (canvas);
}
}
// Add a [Color] Rect on screen
class RectComponent extends Component {
final double screenWidth;
final double screenHeight;
double xStartPosition = 0 ;
double yStartPosition = 0 ;
static double xRectWidth = 50 ;
static double yRectHeight = 50 ;
final paint = Paint ()
..color = Colors .white
..strokeWidth = 4 ;
RectComponent (this .screenWidth, this .screenHeight);
@override
void update (double dt) {
super .update (dt);
xStartPosition = screenWidth / 2 ;
yStartPosition = screenHeight / 2 ;
}
@override
void render (Canvas canvas) {
super .render (canvas);
// xStartPos, yStartPos, xRectWidth, yRectHeight
canvas.drawRect (
Rect .fromLTWH (xStartPosition, yStartPosition, xRectWidth, yRectHeight),
paint);
}
}
// Add a [Color] Line on screen
class LineComponent extends Component {
final double screenWidth;
final double screenHeight;
double xLineP1 = 50 ;
double yLineP1 = 50 ;
double xLineP2 = 250 ;
double yLineP2 = 150 ;
final paint = Paint ()
..color = Colors .white
..strokeWidth = 4 ;
LineComponent (this .screenWidth, this .screenHeight);
// @override
// void update(double dt) {
// super.update(dt);
// }
@override
void render (Canvas canvas) {
super .render (canvas);
Offset p1 = Offset (xLineP1, yLineP1);
Offset p2 = Offset (xLineP2, yLineP2);
final paint = Paint ()
..color = Colors .red
..strokeWidth = 4 ;
canvas.drawLine (p1, p2, paint);
}
}
class CircleComponent extends Component {
final double screenWidth;
final double screenHeight;
double xP1 = 450 ;
double yP1 = 350 ;
CircleComponent (this .screenWidth, this .screenHeight);
// @override
// void update(double dt) {
// super.update(dt);
// }
@override
void render (Canvas canvas) {
Offset p1 = Offset (xP1, yP1);
double radius = 50 ;
final paint = Paint ()
..color = Colors .yellow
..strokeWidth = 4 ;
canvas.drawCircle (p1, radius, paint);
}
}