我正在尝试使用
flame
框架在 flutter canvas 中绘制网格,但确实很难。这是我当前用来绘制网格的代码:
import 'dart:async';
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:learning_flame/my_game.dart';
class GameBoard extends PositionComponent with HasGameRef<MyGame> {
@override
FutureOr<void> onLoad() {
super.onLoad();
// game size
final gameSize = gameRef.size;
const cellSize = 40.0;
const cellSpacing = 10.0;
// starting position
final startingPosition = Vector2(-(gameSize.x / 2) + cellSize, 0);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
add(
Cell(
position: startingPosition +
Vector2(
(cellSize + cellSpacing) * j,
i * (cellSize + cellSpacing),
),
size: Vector2.all(cellSize),
),
);
}
}
}
}
class Cell extends RectangleComponent {
Cell({
required super.position,
required super.size,
}) : super(anchor: Anchor.center);
@override
void render(Canvas canvas) {
super.render(canvas);
canvas.drawRect(
Rect.fromCenter(
center: Offset.zero,
width: position.y,
height: position.x,
),
paint..color = Colors.white,
);
}
}
预期结果
我期望使用提供的代码在画布上绘制 5x5 网格。