Flutter实现区域(组件)截图
在Flutter中,一切皆为组件,截图功能也不例外,Flutter已经为我们提供了RepaintBoundary
组件。话不多说,先来看看效果图:
实现截图步骤:
- 首先用
RepaintBoundary
包裹要截图的Widget - 然后给
RepaintBoundary
设置一个GlobalKey
,如下面代码中的:comGlobalKey
- 最后获取图片数据,如下面代码中的:
toPng()
就是来获取Uint8List
格式的图片数据
完整代码:
- import 'package:flutter/material.dart';
- import 'dart:typed_data';
- import 'dart:ui';
- import 'package:flutter/rendering.dart';
- class DomToImageWidget extends StatelessWidget {
- GlobalKey comGlobalKey;
- Uint8List bytes = Uint8List.fromList([71, 73, 70, 56, 57, 97, 1, 0, 1, 0, 128, 0, 0, 0, 0, 0, 255, 255, 255, 33, 249, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 1, 68, 0, 59]);
- // 获取Uint8List数据
- Future<Uint8List> toPng() async {
- try {
- RenderRepaintBoundary boundary =
- comGlobalKey.currentContext.findRenderObject();
- var image = await boundary.toImage(pixelRatio: 3.0);
- ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
- Uint8List pngBytes = byteData.buffer.asUint8List();
- return pngBytes; //这个对象就是图片数据
- } catch (e) {
- print(e);
- }
- return null;
- }
- @override
- Widget build(BuildContext context) {
- // 通过RepaintBoundary设置截图范围
- return RepaintBoundary(
- key: comGlobalKey,
- child: Column(
- children: <Widget>[
- Container(
- child: Column(
- children: <Widget>[
- Image.network('assets/d28480a9947d80a9ecc858f86e7aef6e.jpg'),
- Text('截图区域')
- ],
- ),
- ),
- RaisedButton(
- child: Text('截图'),
- onPressed: () {
- toPng().then((data) {
- setState(() {
- bytes = data;
- });
- });
- },
- ),
- // 展示截图
- Image.memory(bytes, width: 200, height: 200,)
- ],
- )
- );
- }
- }
我们还可以转为base64格式:
- import 'dart:convert' as convert;
- toPng().then((data) {
- var base64 = convert.base64Encode(data);
- })
当然,如果你要截图全屏,那就用RepaintBoundary
包裹整个应用就可以了。
截图就是这么简单~