Flutter 图片如何充满父布局

正常我们需要显示一张图片,会用到Image这个控件。
打个比方,我们加载一张本地的图片,
先看一下这个Image.asset的源码:

Image.asset(String name, {
    Key key,
    AssetBundle bundle,
    double scale,
    this.width,
    this.height,
    this.color,
    this.colorBlendMode,
    this.fit,
    this.alignment: Alignment.center,
    this.repeat: ImageRepeat.noRepeat,
    this.centerSlice,
    this.matchTextDirection: false,
    this.gaplessPlayback: false,
    String package,
  }) : image = scale != null
         ? new ExactAssetImage(name, bundle: bundle, scale: scale, package: package)
         : new AssetImage(name, bundle: bundle, package: package),
       assert(alignment != null),
       assert(repeat != null),
       assert(matchTextDirection != null),
       super(key: key);

基本上根据这些属性名字就能看出这些属性都是干啥的,这里面咱只看fit这个东西,这里有专门讲解这一块用法的一个文章image,(这里说明一下,由于网上的这篇文章大多都长得一样,本人也没分辨出真正作者是谁,如果该链接文章的作者看到的话可以联系我,我把链接改成你的)

fitDescriptionResult
BoxFit.fill全图显示,显示可能拉伸,充满 《Flutter 图片如何充满父布局》 image
BoxFit.contain全图显示,显示原比例,不需充满 《Flutter 图片如何充满父布局》 image
BoxFit.cover显示可能拉伸,可能裁剪,充满 《Flutter 图片如何充满父布局》 image
BoxFit.fitWidth显示可能拉伸,可能裁剪,宽度充满 《Flutter 图片如何充满父布局》 image
BoxFit.fitHeight显示可能拉伸,可能裁剪,高度充满 《Flutter 图片如何充满父布局》 image
BoxFit.none
BoxFit.scaleDown效果和contain差不多,但是此属性不允许显示超过源图片大小,可小不可大 《Flutter 图片如何充满父布局》 image
Image.asset(
        AssetImages.demo,
        fit: BoxFit.cover,
        )

根据我们的理解,第一个参数为图片名字,fit则是这个图片的scaleType。这里的cover相当于centerCrop。问题这时候来了!!划重点!!单独这么写这个Image的话,这个fit参数是不起作用的。因为这个image没有Size,就是里面的heightwidth这俩参数没有。

解决办法:

  • 外面嵌套一层Column(我觉得这种方法有点高射炮打蚊子的感觉。。)
new Column(
        children: <Widget>[
          new Image.network(
            _parties[index]["cover"], fit: BoxFit.fitWidth,
            height: 120.0,
          ),
          new Text(_parties[index]['name'])
        ]
    )
  • 直接写上宽和高(前提是你得先知道确切的宽高,比如要全屏显示图片)
Image.asset(
      AssetImages.demo,
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      fit: BoxFit.cover,
    )
  • 外面嵌套BoxConstraints,给Image加约束,让它填充父布局。(本人喜欢这种方式)
ConstrainedBox(
        child: Image.asset(
                  AssetImages.start2,
                  fit: BoxFit.cover,
                  ),
        constraints: new BoxConstraints.expand(),
       )

我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=2bwjo723g1z4g

    原文作者:坑吭吭
    原文地址: https://www.jianshu.com/p/8810bacfe5d4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞