正常我們需要顯示一張圖片,會用到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,(這里說明一下,由於網上的這篇文章大多都長得一樣,本人也沒分辨出真正作者是誰,如果該鏈接文章的作者看到的話可以聯系我,我把鏈接改成你的)
| fit | Description | Result |
|---|---|---|
| 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,就是里面的height和width這倆參數沒有。
解決辦法:
- 外面嵌套一層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://www.jianshu.com/p/8810bacfe5d4
