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

塞思·拉德(Seth Ladd):

假设我已经在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。)

谢谢!

科林·杰克逊(Collin Jackson):

更新的解决方案:

随着新版本的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,
        ],
      ),
    );
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Android中获得可用的屏幕宽度和高度

如何在OpenCV中获取图像的宽度和高度?

如何在Flutter中调整IconButton的大小(高度和宽度)

R确定图像的宽度和高度(以像素为单位)

如何在Android中获取显示图像的宽度和高度?

如何在代码中传递图像的宽度和高度

如何在flutter中创建具有固定宽度和高度的颜色框?

如何在网络工作者中获取图像的宽度和高度?

如何在自动表中定义宽度和高度

如何从Glide获取图像的宽度和高度

如何在保持宽高比以及最大宽度和高度的同时批量调整ImageMagick中的图像大小?

如何在CSS中设置蒙版图像的宽度和高度?

如何更改图像的宽度和高度?

如何在SwiftUI中设置图像的宽度和高度?

如何在OpenCV Python中设置框架的高度和宽度

如何设置图像的高度和宽度相同?

如何在Flutter中设置容器内按钮的高度和宽度?

如何在Flutter中更改列的宽度和高度?

确定片段的onCreateView()中的宽度和高度

确定未插入dom的图像的宽度和高度

如何在WPF中根据窗口的宽度和高度调整控件的宽度和高度

如何在jQuery中获取图像高度宽度

如何在js中设置图像对象的高度和宽度

如何在图像C#中设置宽度和高度

如何在xml中交换ImageView的高度和宽度

如何确定缓存网络图像的宽度和高度?

如何在保持响应的同时指定图像的宽度和高度?

如何在css中为内容图像设置宽度和高度

Javascript,如何从 blob 中获取图像宽度和高度?