Flutter 3D模型加载插件gg_gltf的使用

Flutter 3D模型加载插件gg_gltf的使用

gg_gltf 是一个用于解析和生成glTF 3D图形文件的库。

生成代码

flutter pub run build_runner build

示例代码

以下是使用 gg_gltf 加载和显示3D模型的完整示例:

// [@license](/user/license)
// Copyright (c) 2019 - 2024 Dr. Gabriel Gatzsche. All Rights Reserved.
//
// Use of this source code is governed by terms that can be
// found in the LICENSE file in the root of this package.

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:gg_gltf/gg_gltf.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('gg_gltf 示例'),
        ),
        body: Center(
          child: GltfModel(
            gltf: Gltf.example,
            fit: BoxFit.contain,
          ),
        ),
      ),
    );
  }
}
1 回复

更多关于Flutter 3D模型加载插件gg_gltf的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


gg_gltf 是一个用于在 Flutter 应用中加载和显示 3D 模型的插件,支持 GLTF 和 GLB 格式的 3D 模型。GLTF(GL Transmission Format)是一种用于传输和加载 3D 模型的开放标准格式,广泛应用于 3D 图形领域。

安装 gg_gltf 插件

首先,你需要在 pubspec.yaml 文件中添加 gg_gltf 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  gg_gltf: ^0.1.0  # 请检查最新版本

然后运行 flutter pub get 来安装依赖。

使用 gg_gltf 加载和显示 3D 模型

以下是一个简单的示例,展示如何使用 gg_gltf 插件加载和显示一个 GLTF 模型。

import 'package:flutter/material.dart';
import 'package:gg_gltf/gg_gltf.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('3D Model Viewer'),
        ),
        body: Center(
          child: GLTFViewer(
            assetPath: 'assets/models/your_model.gltf', // 替换为你的 GLTF 文件路径
          ),
        ),
      ),
    );
  }
}

class GLTFViewer extends StatelessWidget {
  final String assetPath;

  GLTFViewer({required this.assetPath});

  @override
  Widget build(BuildContext context) {
    return GGGLTFViewer(
      assetPath: assetPath,
      scale: Vector3(1.0, 1.0, 1.0), // 缩放比例
      position: Vector3(0.0, 0.0, 0.0), // 模型位置
      rotation: Vector3(0.0, 0.0, 0.0), // 模型旋转
      backgroundColor: Colors.white, // 背景颜色
      onModelLoaded: () {
        print('3D Model loaded successfully');
      },
      onError: (error) {
        print('Failed to load 3D model: $error');
      },
    );
  }
}

代码说明

  1. GGGLTFViewer: 这是 gg_gltf 插件提供的主要组件,用于加载和显示 3D 模型。

    • assetPath: 指定 GLTF 或 GLB 文件的路径。文件需要放在 assets 目录下,并在 pubspec.yaml 中声明。
    • scale: 控制模型的缩放比例。
    • position: 控制模型在场景中的位置。
    • rotation: 控制模型的旋转角度。
    • backgroundColor: 设置场景的背景颜色。
    • onModelLoaded: 模型加载成功时的回调函数。
    • onError: 模型加载失败时的回调函数。
  2. Vector3: 用于表示三维向量,通常用于表示位置、缩放和旋转。

添加 GLTF 文件到项目中

将你的 GLTF 或 GLB 文件放在 assets/models/ 目录下,并在 pubspec.yaml 中声明:

flutter:
  assets:
    - assets/models/your_model.gltf
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!