我的图片与设备屏幕的纵横比不匹配。我想拉伸(stretch)图像以使其完全填满屏幕,并且我不想裁剪图像的任何部分。
CSS 有百分比的概念,所以我可以将高度和宽度设置为 100%。但是Flutter好像没有这个概念,只硬编码高度和宽度是不好的,所以我卡住了。
这就是我所拥有的(我正在使用堆栈,因为我在图像的前景中有一些东西):
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,
],
);
最佳答案
要使 Image 填充其父级,只需将其包装到 FittedBox
中:
FittedBox(
child: Image.asset('foo.png'),
fit: BoxFit.fill,
)
FittedBox
这里将拉伸(stretch)图像以填充空间。
(请注意,此功能过去由 BoxFit.fill
提供,但同时 API 已更改,因此 BoxFit
不再提供此功能。FittedBox
应该可以作为替代品使用,不需要对构造函数参数进行任何更改。)
或者,对于复杂的装饰,您可以使用 Container
而不是 Image
- 并使用 decoration
/foregroundDecoration
字段。
要使 Container
成为其父级,它应该:
alignment
属性而不是 null
这是一个将两个图像和一个 Text
组合在一个 Container
中的示例,同时采用其父级的 100% 宽度/高度:
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),
),
),
关于image - 如何在 Flutter 中拉伸(stretch)图像以适合整个背景(100% 高度 x 100% 宽度)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45745448/
相关文章:
flutter - 如何使用主题通用更改AppBar的文本颜色,FAB的图标颜色?
generics - 为什么有状态的小部件在flutter中定义为两个类?
flutter - Flutter 中 SliverList 与 ListView 的区别
dart - 如何在 flutter 中创建工具栏搜索 View
dart - Flutter - 更改 OutlineInputBorder 的边框颜色
json - 类型 'List
flutter - 如何在 Flutter 中将图像和文件上传到服务器?