/**
截取一部分组件作为图片
* const RepaintBoundary({ Key key, Widget child })
*/
//import 'dart:io';
//import 'dart:typed_data';
//import 'package:flutter/material.dart';
//import 'package:flutter/rendering.dart';
//import 'dart:ui';
//import 'package:path_provider/path_provider.dart';
class Widget_RepaintBoundary_State extends State<Widget_RepaintBoundary_Page> {
GlobalKey globalKey = new GlobalKey();
Future<File> _capture() async {
try {
RenderRepaintBoundary boundary = globalKey.currentContext
.findRenderObject();
//boundary.toImage()转化为ui.Image对象,不会自动为包裹的组件添加背景,不设置可能会缺失背景
var image = await boundary.toImage(pixelRatio: window.devicePixelRatio);
//将image转化为byteData
ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
//这个对象就是图片数据
Uint8List pngBytes = byteData.buffer.asUint8List();
String sTempDir = (await getTemporaryDirectory()).path;
bool isDirExist = await Directory(sTempDir).exists();
if (!isDirExist) {
Directory(sTempDir).create();
}
Future<File> file = File(sTempDir + "/abc.png").writeAsBytes(pngBytes);
return file;
} catch (e) {
print(e);
}
return null;
}
@override
Widget build(BuildContext context) {
var file = "/data/user/0/com.yourcompany.test1/cache/abc.png";
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("RepaintBoundary"),
),
body: Column(
children: <Widget>[
RepaintBoundary(
key: globalKey,
child: Text("RepaintBoundary组件"),
),
RaisedButton(
onPressed: () {
_capture().then((_file){
setState(() {
debugPrint(_file.path);
file = _file.path;
});
}).whenComplete((){
});
}
),
Image.asset(file),
],
)
),
);
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。