0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FlutterでWidgetを画像として取得する

Posted at

widgetを画像として取得

概要

widgetを画像として取得する際には、[[RepaintBoundaryウィジェット]]を使用する。

RepaintBoundaryウィジェット

概要

RepaintBoundaryウィジェットは、Flutterでパフォーマンスを向上させるために使用される重要なツールである。
また、子要素を画像データにすることのできる要素である。

解説

以下の例では、[[Containerウィジェット]]を画像として取得することができる。

@override
Widget build(BuildContext context) {
	return RepaintBoundary(
	  key: _globalKey,
	  child: Container(
		width: 100,
		height: 100,
		color: Colors.red,
	  ),
	);
}

画像を取得するコードは以下のとおりである。

import 'dart:ui' as ui;

...

 Future<void> captureImage() async {
    RenderRepaintBoundary boundary = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundary.toImage();
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    setState(() {
      _imageData = byteData!.buffer.asUint8List();
    });
 }

コード例

import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

class MyWidget extends StatefulWidget {
 @override
 _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
 GlobalKey _globalKey = GlobalKey();
 Uint8List? _imageData;

 @override
 Widget build(BuildContext context) {
    return RepaintBoundary(
      key: _globalKey,
      child: Container(
        width: 100,
        height: 100,
        color: Colors.red,
      ),
    );
 }

 Future<void> captureImage() async {
    RenderRepaintBoundary boundary = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundary.toImage();
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    setState(() {
      _imageData = byteData!.buffer.asUint8List();
    });
 }
}

プロパティ

プロパティ名 概要 備考
child 子要素をここに入れる。

データの変換 (Realm保存用)

byteData -> base64

Future<String> convertBoundaryToImageBase64(RenderRepaintBoundary boundary) async {
	ui.Image image = await boundary.toImage();
	ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
	Uint8List imageData = byteData!.buffer.asUint8List();
	String imageDataBinary = base64Encode(imageData);
	return imageDataBinary;
}

base64 -> imageProvider

ImageProvider convertBase64ToImage(String base64) {
	Uint8List bytes = base64Decode(base64.split(',').last);
	ImageProvider imageProvider = Image.memory(bytes).image;
	return imageProvider;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?