项目背景
随着项目的不断完善,需要向外推广app,微信分享就是一个很常用的方式,我们常用webPage分享,这次我们扩展为图片截图并分享到朋友圈,效果图如下:
Flutter中截图的主要用到了类RepaintBoundary。
1、在需要截图的widget外包裹一层RepaintBoundary
RepaintBoundary(
key: repaintWidgetKey,
child: Container(
width: _boxWidth + Adapter.px(30),
height:_boxHeight + Adapter.px(isPhone ? 30 : 44),
padding: EdgeInsets.only(top: Adapter.px(10), bottom: Adapter.px(isPhone ? 20 : 34), left: Adapter.px(15), right: Adapter.px(15)),
color: Color(0xFFD3F4FD),
child: Container(
width: _boxWidth,
height: _boxHeight,
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
offset: Offset(0, Adapter.px(2)),
blurRadius: Adapter.px(14),
color: Color(0x29000000),
spreadRadius: 0,
)
],
borderRadius: BorderRadius.circular(_borderRadius),
),
child: Stack(
children: <Widget>[
_renderRecord(),
_renderDivider(),
_renderDownTip(),
_renderQRCode(),
],
)),
),
)
需要传入一个GlobalKey()
GlobalKey repaintWidgetKey = GlobalKey(); // 绘图key值
2、将截屏的图片生成ByteData
import 'dart:ui' as ui;
import 'dart:async';
/// 截屏图片生成图片流ByteData
Future<ByteData> _capturePngToByteData() async {
try {
RenderRepaintBoundary boundary = repaintWidgetKey.currentContext
.findRenderObject();
double dpr = ui.window.devicePixelRatio; // 获取当前设备的像素比
ui.Image image = await boundary.toImage(pixelRatio: dpr);
ByteData _byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return _byteData;
} catch (e) {
print(e);
}
return null;
}
3、将ByteData写入File,并执行微信图片分享
import 'dart:ui' as ui;
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
/// 把图片ByteData写入File,并触发微信分享
Future<Null> _shareUiImage() async {
ByteData sourceByteData = await _capturePngToByteData();
Uint8List sourceBytes = sourceByteData.buffer.asUint8List();
Directory tempDir = await getTemporaryDirectory();
String storagePath = tempDir.path;
File file = new File('$storagePath/报告截图.png');
if (!file.existsSync()) {
file.createSync();
}
file.writeAsBytesSync(sourceBytes);
eventManager.eventBus
.fire(ShareEvent(pageReport, shareType: 'image', file: file, desc: '报告图片'));
}
4、执行微信图片分享
fluwx.shareToWeChat(fluwx.WeChatShareImageModel.fromFile(
shareEvent.file,
description: shareEvent.desc,
scene: scene));
网友评论