如何在画布上绘制网格?

问题描述 投票:0回答:1

我正在尝试使用

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,
    );
  }
}

这是我得到的结果: code result

预期结果

我期望使用提供的代码在画布上绘制 5x5 网格。

flutter canvas flame
1个回答
0
投票

这解决了这个问题: https://github.com/flame-engine/flame/issues/3337

我没有正确使用

RectangleComponent

© www.soinside.com 2019 - 2024. All rights reserved.