You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Flame中如何处理PNG纹理图集(类似Love2D的Quad)

在Flutter Flame中实现类似Love2D的Quad功能

Love2D的Quad本质是从单张纹理图集中截取指定区域生成独立精灵,在Flame里无需依赖.fa格式的Fire Atlas,直接通过Sprite类的srcRect参数就能实现相同效果,最终转为SpriteComponent使用。以下是具体实现步骤:

1. 配置资源

将Kenney扑克牌图集的tilesheet图片放入项目assets目录,在pubspec.yaml中声明资源路径:

flutter:
  assets:
    - assets/playing_cards_tilesheet.png

2. 从图集中截取指定区域生成SpriteComponent

手动截取单个精灵

先加载整张图集纹理,再通过Rect定义要截取的区域(对应Love2D中Quad的坐标参数),最后创建SpriteComponent:

import 'package:flame/components.dart';
import 'package:flame/flame.dart';
import 'package:flame/game.dart';

class CardGame extends FlameGame {
  @override
  Future<void> onLoad() async {
    // 加载整张图集
    final atlasImage = await Flame.images.load('playing_cards_tilesheet.png');
    
    // 定义截取区域:左上角坐标(71, 0),宽71,高96(对应第二张牌)
    final cardRect = Rect.fromLTWH(71, 0, 71, 96);
    // 创建Sprite并指定截取区域
    final cardSprite = Sprite(atlasImage, srcRect: cardRect);
    // 转为SpriteComponent并添加到游戏
    add(SpriteComponent(sprite: cardSprite, size: Vector2(71, 96)));
  }
}

批量生成精灵(遍历图集)

如果图集内子图尺寸统一,可以通过循环计算每个子图的srcRect,批量生成精灵:

// 假设每个扑克牌尺寸为71x96,图集共5行13列
const double cardWidth = 71;
const double cardHeight = 96;
const int rows = 5;
const int cols = 13;

for (int row = 0; row < rows; row++) {
  for (int col = 0; col < cols; col++) {
    final srcRect = Rect.fromLTWH(
      col * cardWidth,
      row * cardHeight,
      cardWidth,
      cardHeight,
    );
    final sprite = Sprite(atlasImage, srcRect: srcRect);
    // 给每个精灵设置不同位置
    add(SpriteComponent(
      sprite: sprite,
      size: Vector2(cardWidth, cardHeight),
      position: Vector2(col * cardWidth, row * cardHeight),
    ));
  }
}

3. 替代方案:使用单张图片

如果图集方案不适用,直接加载单张扑克牌图片生成SpriteComponent:

final singleCardComponent = await SpriteComponent.load(
  'ace_of_spades.png',
  size: Vector2(71, 96),
);
add(singleCardComponent);

内容的提问来源于stack exchange,提问作者shingo.nakanishi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 17:35:11