一尘不染

如何确定Flutter中图像的宽度和高度?

flutter

假设我已经在pubspec.yaml中声明了我的图像,如下所示:

  assets:
    - assets/kitten.jpg

我的Flutter代码是这样的:

void main() {
  runApp(
    new Center(
      child: new Image.asset('assets/kitten.jpg'),
    ),
  );
}

既然有了new Image.asset(),如何确定该图像的宽度和高度?例如,我只想打印出图像的宽度和高度。

(看起来dart:ui的Image类具有宽度和高度,但不确定如何从小部件的Image转到dart:ui的Image。)

谢谢!


阅读 1487

收藏
2020-08-13

共1个答案

一尘不染

更新的解决方案:

随着新版本的flutter,旧解决方案已过时。现在addListener需要ImageStreamListener

Widget build(BuildContext context) {
    Image image = new Image.network('https://i.stack.imgur.com/lkd0a.png');
    Completer<ui.Image> completer = new Completer<ui.Image>();
    image.image
      .resolve(new ImageConfiguration())
      .addListener(ImageStreamListener(ImageInfo info, bool _) { 
        completer.complete(info.image));
      })
    ...
    ...

原始版本:

如果您已经有一个Image小部件,则可以ImageStream通过调用它来读取resolve它的内容ImageProvider

屏幕截图

import 'dart:ui' as ui;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {

  Widget build(BuildContext context) {
    Image image = new Image.network('https://i.stack.imgur.com/lkd0a.png');
    Completer<ui.Image> completer = new Completer<ui.Image>();
    image.image
      .resolve(new ImageConfiguration())
      .addListener((ImageInfo info, bool _) => completer.complete(info.image));
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Image Dimensions Example"),
      ),
      body: new ListView(
        children: [
          new FutureBuilder<ui.Image>(
            future: completer.future,
            builder: (BuildContext context, AsyncSnapshot<ui.Image> snapshot) {
              if (snapshot.hasData) {
                return new Text(
                  '${snapshot.data.width}x${snapshot.data.height}',
                  style: Theme.of(context).textTheme.display3,
                );
              } else {
                return new Text('Loading...');
              }
            },
          ),
          image,
        ],
      ),
    );
  }
}
2020-08-13