如何在Flutter中拉伸图像以适合整个背景(高度100%x宽度100%)? [英] How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?
问题描述
我的图像与设备屏幕的纵横比不匹配。我想拉伸图像以使其完全填满屏幕,并且不想裁剪图像的任何部分。
I have an image that doesn't match the aspect ratio of my device's screen. I want to stretch the image so that it fully fills the screen, and I don't want to crop any part of the image.
CSS具有百分比的概念,因此我可以将高度和宽度设置为100%。但是Flutter似乎没有这个概念,仅对高度和宽度进行硬编码是很不好的,所以我被卡住了。
CSS has the concept of percentages, so I could just set height and width to 100%. But it doesn't seem like Flutter has that concept, and it's bad to just hard code the height and width, so I'm stuck.
这就是我所拥有的(我正在使用堆栈,因为图像的前景中有东西):
Here's what I have (I'm using a Stack since I have something in the foreground of the image):
Widget background = new Container(
height: // Not sure what to put here!
width: // Not sure what to put here!
child: new Image.asset(
asset.background,
fit: BoxFit.fill, // I thought this would fill up my Container but it doesn't
),
);
return new Stack(
children: <Widget>[
background,
foreground,
],
);
推荐答案
要使图像填充其父级,只需将其包装放入 FittedBox
:
To make an Image fill its parent, simply wrap it into a FittedBox
:
FittedBox(
child: Image.asset('foo.png'),
fit: BoxFit.fill,
)
FittedBox
在这里将拉伸图像以填充空间。
(请注意,此功能以前是由 BoxFit.fill
提供的,但与此同时,API进行了更改,使得 BoxFit
不再提供此功能。 FittedBox
应该可以直接替换,而无需更改构造函数参数。)
FittedBox
here will stretch the image to fill the space.
(Note that this functionality used to be provided by BoxFit.fill
, but the API has meanwhile changed such that BoxFit
no longer provides this functionality. FittedBox
should work as a drop-in replacement, no changes need to be made to the constructor arguments.)
或者,对于复杂的装饰,可以使用 Container
代替图片
–并使用装饰
/ foregroundDecoration
字段。
Alternatively, for complex decorations you can use a Container
instead of an Image
– and use decoration
/foregroundDecoration
fields.
要使容器
成为其父对象,它应该:
To make the Container
will its parent, it should either:
- 没有孩子
- 具有
alignment
属性而不是null
- have no child
- have
alignment
property notnull
在此示例中,将两个图像和一个 Text
合并为一个示例容器
,同时采用其父级宽度/高度的100%:
Here's an example that combines two images and a Text
in a single Container
, while taking 100% width/height of its parent:
Container(
foregroundDecoration: const BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'https://p6.storage.canalblog.com/69/50/922142/85510911_o.png'),
fit: BoxFit.fill),
),
decoration: const BoxDecoration(
image: DecorationImage(
alignment: Alignment(-.2, 0),
image: NetworkImage(
'http://www.naturerights.com/blog/wp-content/uploads/2017/12/Taranaki-NR-post-1170x550.png'),
fit: BoxFit.cover),
),
alignment: Alignment.bottomCenter,
padding: EdgeInsets.only(bottom: 20),
child: Text(
"Hello World",
style: Theme.of(context)
.textTheme
.display1
.copyWith(color: Colors.white),
),
),
这篇关于如何在Flutter中拉伸图像以适合整个背景(高度100%x宽度100%)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!