如何在Flutter中将图像拉伸以适应整个背景(100%高度x100%宽度)?

137
我有一张图片,它的长宽比与设备屏幕不匹配。我想要拉伸这张图片,使其完全填满屏幕,并且不裁剪任何部分。
CSS 有百分比的概念,所以我可以将高度和宽度设置为100%。但是 Flutter 似乎没有这个概念,而且硬编码高度和宽度是不好的,所以我陷入了困境。
这是我的代码(我正在使用 Stack,因为我在图片前景中有其他内容):
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,
  ],
);
19个回答

4

访问 https://youtu.be/TQ32vqvMR80

例如,如果父容器的高度为200,则

Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: NetworkImage('url'),
                fit: BoxFit.cover,
              ),
            ),
          ),

3

如果您想在Flutter中添加适合的背景图像,以下方法可行:

class Myname extends StatelessWidget {
  const Myname({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/aj.jpg"),
              fit: BoxFit.cover,
            ),
          ),
          child: Scaffold(
            backgroundColor: Colors.transparent,
            body: Column(),
          ),
        ),
      ),
    );
  }
}

现在您可以将其他内容添加到Column()


3

我将容器的宽度和高度设置为double.infinity,例如:

Container(
        width: double.infinity,
        height: double.infinity,
        child: //your child
)

这对容器的子元素不起作用,只对容器本身起作用。 - Ojonugwa Jude Ochalifu

2

在填充方面,我有时会使用SizedBox.expand。


2

我在使用FittedBox时遇到了一些问题,所以我将我的图片包装在一个LayoutBuilder中:

LayoutBuilder( 
   builder: (_, constraints) => Image(
      fit: BoxFit.fill,
      width: constraints.maxWidth,
      image: AssetImage(assets.example),
   ),
)

这个方法非常有效,我建议你试一下。
当然,你也可以使用高度而不是宽度,这只是我的做法。

1

对于我来说,在有限制的容器中使用Image(fit: BoxFit.fill ...)可以解决问题。


1

这对我有效

class _SplashScreenState extends State<SplashScreen> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: FittedBox(
        child: Image.asset("images/my_image.png"),
        fit: BoxFit.fill,
      ),);
  }
}

0

我在这篇文章中没有找到答案,但是我找到了解决方法:

        Positioned(
            bottom: 0,
            top: 0,
            child: Image.asset(
          'assets/images/package_bg.png',
        )),

这段代码使图像适应堆栈的高度。


0
尝试设置 contentPadding
ListTile(
  contentPadding: EdgeInsets.all(0.0),
  ...
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接