PR

[Flutter]Widgetを画像に書き出す方法

Flutter

はじめに

Flutterでアプリを作っているときに「Widgetを画像に書き出したいなぁ」とふと思い、調べてみたら方法があったので、メモです。

環境

  • Flutter 2.5.3

参考

なんとFlutter Communityのブログに載っていました。

やり方はRepaintBoundarykeyをつけて、そこから画像を抽出するといった感じです。

Export your widget to image with flutter
Some days ago I was messing around with flutter and thought that everything in flutter is rendered pixel by pixel so the...

サンプルコード

今回はこのブログのFlutterの画像に太陽のアイコンを追加してImageへ書き出すサンプルです。

import 'dart:ui' as ui;

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

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

class MyApp extends StatelessWidget {
  const MyApp({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _globalKey = GlobalKey();
  Image? _image;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FittedBox(
              fit: BoxFit.scaleDown,
              child: RepaintBoundary(
                key: _globalKey,
                child: Stack(
                  children: [
                    SizedBox(
                      width: 1024,
                      height: 1024,
                      child: Image.network(
                        'https://nobushiueshi.com/wp-content/uploads/common/flutter_logo_white-1.png',
                      ),
                    ),
                    const Positioned(
                      top: 256,
                      left: 64,
                      child: Icon(
                        Icons.wb_sunny,
                        color: Colors.orange,
                        size: 128,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: Center(
                child: _image ?? const Text("画像はまだない"),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _doCapture,
        tooltip: 'Capture',
        child: const Icon(Icons.copy),
      ),
    );
  }

  Future<void> _doCapture() async {
    final image = await _convertWidgetToImage();
    setState(() {
      _image = image;
    });
  }

  Future<Image?> _convertWidgetToImage() async {
    try {
      final boundary = _globalKey.currentContext!.findRenderObject()
          as RenderRepaintBoundary;
      final image = await boundary.toImage(pixelRatio: 3.0);
      final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      var pngBytes = byteData!.buffer.asUint8List();
      return Image.memory(pngBytes);
    } catch (e) {
      print(e);
    }
    return null;
  }
}

結果

ボタンを押すと。。。

無事、Imageへ書き出されました。

さいごに

なにかに使えるかもしれないけど、何にも使えないかもしれない。。。

おすすめ参考書

参考

【Flutter】WidgetからImageを生成する方法(Widgetのキャプチャ) - 株式会社イーガオ
こんにちは。 スマホアプリをメインに開発しているロッキーカナイです。 Flutter関連の記事を載せさせてもらっている関係で、何か面白いことができないかとネットを漁っていたら、こんな記事を見つけました。 Flutter

コメント

タイトルとURLをコピーしました