Flutter之屏幕截圖/組件截圖

繼續更新Flutter系列,本篇記錄如何在Flutter中進行截圖,在Flutter中萬物皆組件,不但高斯模糊是套一層組件,截圖也是套一層組件,因此屏幕截圖和組件截圖實際上是一個意思。雖然Flutter的這種嵌套UI很繁瑣,可是用習慣了反而會感受結構很清晰,不用擔憂佈局相關代碼的混亂,在FlutterInspector識圖下更是一目瞭然,能夠在不翻閱代碼的狀況下快速理解別人寫的佈局。
本次用到的組件是RepaintBoundary,效果圖:
app

效果展現

建立Flutter工程

依照慣例,建立一個簡單的Flutter工程,清理main.dart中無用的代碼便於演示:less

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(),
    );
  }
}

複製代碼

這就是一個帶有標題欄的空界面。async

寫一個簡單的場景

便於演示,在這個界面中加入一個gif圖片,固然你用普通圖片或者視頻也是能夠的:ide

class _MyHomePageState extends State<MyHomePage> {
  Future<Uint8List> _capturePng() async {
    //TODO 進行截圖
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[ Image.network( "http://qiniu.nightfarmer.top/test.gif", width: 300, height: 300, ), FlatButton( onPressed: () { this._capturePng(); }, child: Text("全屏截圖"), ), ], ), ); } } 複製代碼

加入圖片以後我順便加入了一個FlatButton組件,經過這個點擊這個按鈕來觸發截圖的邏輯。
固然到目前爲止這仍是隻是一個簡單的界面佈局,沒有用到任何新的東西。佈局

如何截圖

前面說到本篇會用到RepaintBoundary組件,接下來把它套在你想要截圖的組件的外層,想截全屏的話就套在最外面就能夠,Flutter的這種寫法習慣就好。
同時定義一個Key用來操做這個組件ui

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey rootWidgetKey = GlobalKey();
  ...

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: rootWidgetKey,
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          .....
        ),
      ),
    );
  }
}
複製代碼

經過rootWidgetKey能夠拿到RenderRepaintBoundary的引用,進來拿到內部組件的截圖:this

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey rootWidgetKey = GlobalKey();

  Future<Uint8List> _capturePng() async {
    try {
      RenderRepaintBoundary boundary =
          rootWidgetKey.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;
  }
  ...
}
複製代碼

經過上面一系列的方法調用,就拿到了一個Unit8List類型的圖片數據。spa

顯示截圖

而Unit8List類型的圖片數據的顯示也很是簡單,經過Image.memory方法從內存中加載圖片,下面附上完整的State代碼:.net

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey rootWidgetKey = GlobalKey();

  List<Uint8List> images = List();

  _capturePng() async {
    try {
      RenderRepaintBoundary boundary =
          rootWidgetKey.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      images.add(pngBytes);
      setState(() {});
      return pngBytes;
    } catch (e) {
      print(e);
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: rootWidgetKey,
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          children: <Widget>[ Image.network( "http://qiniu.nightfarmer.top/test.gif", width: 300, height: 300, ), FlatButton( onPressed: () { this._capturePng(); }, child: Text("全屏截圖"), ), Expanded( child: ListView.builder( itemBuilder: (context, index) { return Image.memory( images[index], fit: BoxFit.cover, ); }, itemCount: images.length, scrollDirection: Axis.horizontal, ), ) ], ), ), ); } } 複製代碼

完工。code


更多幹貨移步個人我的博客 www.nightfarmer.top/

相關文章
相關標籤/搜索