Flutter 将文字转换成图片(widget转换成图片)并下载

需求

需要根据用户名字生成头像,并进行下载

依赖

用于图片下载的插件:download 1.0.0
地址:https://pub.dev/packages/download

思路

1、flutter 中 组件RepaintBoundary和RenderRepaintBoundary可用于将widget转换成图片
2、使用RepaintBoundary将组件包裹,使用RenderRepaintBoundary 进行处理,可以生成该图片的Uint8List字节数组
3、然后使用Image.memory()可将图片展示
4、使用download 插件将图片下载

代码

import 'dart:typed_data';

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

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

class MyApp extends StatelessWidget {
    
    
  const MyApp({
    
    super.key});

  
  Widget build(BuildContext context) {
    
    
    return MaterialApp(
      home: Scaffold(body: PngHome()),
    );
  }
}

class PngHome extends StatefulWidget {
    
    
  const PngHome({
    
    Key? key}) : super(key: key);

  
  State<PngHome> createState() => _PngHomeState();
}

class _PngHomeState extends State<PngHome> {
    
    
  GlobalKey globalKey = GlobalKey();
  List<Uint8List> images = [];

  void _download(Uint8List pic) {
    
    
    final stream = Stream.fromIterable(pic);
    download(stream, 'hello.png');
    print("下载");
  }

  Future<void> _capturePng() async {
    
    
    final RenderRepaintBoundary boundary =
        globalKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;

    if (boundary.debugNeedsPaint) {
    
    
      print("Waiting for boundary to be painted.");
      await Future.delayed(const Duration(milliseconds: 20));
      return _capturePng();
    }

    final ui.Image image = await boundary.toImage();
    final ByteData? byteData =
        await image.toByteData(format: ui.ImageByteFormat.png);
    final Uint8List pngBytes = byteData!.buffer.asUint8List();
    images.add(pngBytes);

    print(pngBytes);
    setState(() {
    
    });
  }

  
  Widget build(BuildContext context) {
    
    
    return Scaffold(
        body: Container(
      color: Colors.white,
      child: Column(
        children: [
          Container(
            child: RepaintBoundary(
              key: globalKey,
              child: Container(
                width: 150,
                height: 150,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Colors.blue,
                    border: Border.all(width: 1, color: Colors.blue),
                    borderRadius: const BorderRadius.all(Radius.circular(75))),
                child: const Text(
                  '张三',
                  textDirection: TextDirection.ltr,
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
          MaterialButton(
              onPressed: _capturePng,
              child: const Text('生成图片', textDirection: TextDirection.ltr)),
          Expanded(
            child: ListView.builder(
                itemCount: images.length,
                itemBuilder: (context, index) {
    
    
                  return Image.memory(
                    images[index],
                    width: 50,
                    height: 50,
                  );
                }),
          ),
          MaterialButton(
            onPressed: (() {
    
    
              _download(images[0]);
            }),
            child: const Text("下载"),
          )
        ],
      ),
    ));
  }
}

效果

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45634989/article/details/129142935