How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

后端 未结 12 1092
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 00:10

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 par

12条回答
  •  半阙折子戏
    2020-12-01 00:43

    To make an Image fill its parent, simply wrap it into a FittedBox:

    FittedBox(
      child: Image.asset('foo.png'),
      fit: BoxFit.fill,
    )
    

    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.)


    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:

    • have no child
    • have alignment property not null

    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),
      ),
    ),
    

提交回复
热议问题