Flutter之屏幕截圖/組件截圖

繼續(xù)更新Flutter系列,本篇記錄如何在Flutter中進行截圖,在Flutter中萬物皆組件,不但高斯模糊是套一層組件,截圖也是套一層組件,所以屏幕截圖和組件截圖其實是一個意思。雖然Flutter的這種嵌套UI很繁瑣,但是用習(xí)慣了反而會感覺結(jié)構(gòu)很清晰,不用擔(dān)心布局相關(guān)代碼的混亂,在FlutterInspector識圖下更是一目了然,可以在不翻閱代碼的情況下快速理解別人寫的布局。
本次用到的組件是RepaintBoundary,效果圖:

效果展示
效果展示

創(chuàng)建Flutter工程

依照慣例,創(chuàng)建一個簡單的Flutter工程,清理main.dart中無用的代碼便于演示:

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(),
    );
  }
}

這就是一個帶有標(biāo)題欄的空界面。

寫一個簡單的場景

便于演示,在這個界面中加入一個gif圖片,當(dāng)然你用普通圖片或者視頻也是可以的:

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組件,通過這個點擊這個按鈕來觸發(fā)截圖的邏輯。
當(dāng)然到目前為止這還是只是一個簡單的界面布局,沒有用到任何新的東西。

如何截圖

前面說到本篇會用到RepaintBoundary組件,接下來把它套在你想要截圖的組件的外層,想截全屏的話就套在最外面就可以,F(xiàn)lutter的這種寫法習(xí)慣就好。
同時定義一個Key用來操作這個組件

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的引用,進來拿到內(nèi)部組件的截圖:

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;//這個對象就是圖片數(shù)據(jù)
    } catch (e) {
      print(e);
    }
    return null;
  }
  ...
}

通過上面一系列的方法調(diào)用,就拿到了一個Unit8List類型的圖片數(shù)據(jù)。

顯示截圖

而Unit8List類型的圖片數(shù)據(jù)的顯示也非常簡單,通過Image.memory方法從內(nèi)存中加載圖片,下面附上完整的State代碼:

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,
              ),
            )
          ],
        ),
      ),
    );
  }
}

完工。

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容