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 全图显示,显示可能拉伸,充满
 
image
BoxFit.contain 全图显示,显示原比例,不需充满
 
image
BoxFit.cover 显示可能拉伸,可能裁剪,充满
 
image
BoxFit.fitWidth 显示可能拉伸,可能裁剪,宽度充满
 
image
BoxFit.fitHeight 显示可能拉伸,可能裁剪,高度充满
 
image
BoxFit.none    
BoxFit.scaleDown 效果和contain差不多,但是此属性不允许显示超过源图片大小,可小不可大
 
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,
       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://www.jianshu.com/p/8810bacfe5d4

原文地址:https://www.cnblogs.com/ckAng/p/10531786.html